Failed Conditions
Branch issue#666 (91903a)
by Guilherme
08:25
created

PersonController::revokeAuthorizationAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 2
dl 0
loc 14
ccs 0
cts 8
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\CoreBundle\Controller;
12
13
use LoginCidadao\BadgesControlBundle\Handler\BadgesHandler;
14
use LoginCidadao\CoreBundle\Entity\Authorization;
15
use LoginCidadao\CoreBundle\Model\PersonInterface;
16
use LoginCidadao\OAuthBundle\Entity\ClientRepository;
17
use Symfony\Component\HttpFoundation\RedirectResponse;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
23
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
24
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
25
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
26
use FOS\UserBundle\FOSUserEvents;
27
use FOS\UserBundle\Event\FilterUserResponseEvent;
28
use FOS\UserBundle\Util\TokenGenerator;
29
use FOS\UserBundle\Event\GetResponseUserEvent;
30
use FOS\UserBundle\Event\FormEvent;
31
use LoginCidadao\CoreBundle\EventListener\ProfileEditListener;
32
use LoginCidadao\CoreBundle\Form\Type\DocRgFormType;
33
use LoginCidadao\CoreBundle\Entity\IdCard;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\Form\FormError;
36
use LoginCidadao\CoreBundle\Helper\GridHelper;
37
use Symfony\Component\Translation\TranslatorInterface;
38
39
class PersonController extends Controller
40
{
41
    /**
42
     * @Route("/person/authorization/{clientId}/revoke", name="lc_revoke")
43
     * @Template()
44
     */
45
    public function revokeAuthorizationAction(Request $request, $clientId)
46
    {
47
        $form = $this->createForm('LoginCidadao\CoreBundle\Form\Type\RevokeAuthorizationFormType');
48
        $form->handleRequest($request);
49
50
        if ($form->isValid()) {
51
            $this->revoke($clientId);
52
        } else {
53
            $this->addFlash('error', $this->trans("Wasn't possible to disable this service."));
54
        }
55
56
        $url = $this->generateUrl('lc_app_details', ['clientId' => $clientId]);
57
58
        return $this->redirect($url);
59
    }
60
61
    /**
62
     * @Route("/person/checkEmailAvailable", name="lc_email_available")
63
     */
64
    public function checkEmailAvailableAction(Request $request)
65
    {
66
        $translator = $this->get('translator');
67
        $email = $request->get('email');
68
69
        $person = $this->getDoctrine()
70
            ->getRepository('LoginCidadaoCoreBundle:Person')
71
            ->findBy(['email' => $email]);
72
73
        $data = ['valid' => true];
74
        if (count($person) > 0) {
75
            $data = [
76
                'valid' => false,
77
                'message' => $translator->trans('The email is already used'),
78
            ];
79
        }
80
81
        $response = new JsonResponse();
82
        $response->setData($data);
83
84
        return $response;
85
    }
86
87
    /**
88
     * @Route("/profile/change-username", name="lc_update_username")
89
     * @Security("has_role('FEATURE_EDIT_USERNAME')")
90
     * @Template()
91
     */
92
    public function updateUsernameAction(Request $request)
93
    {
94
        $user = $this->getUser();
95
        $userManager = $this->get('fos_user.user_manager');
96
97
        $formBuilder = $this->createFormBuilder($user)
98
            ->add('username', 'Symfony\Component\Form\Extension\Core\Type\TextType')
99
            ->add('save', 'Symfony\Component\Form\Extension\Core\Type\SubmitType');
100
101
        $emptyPassword = strlen($user->getPassword()) == 0;
102
        if ($emptyPassword) {
103
            $formBuilder->add('plainPassword',
104
                'Symfony\Component\Form\Extension\Core\Type\RepeatedType',
105
                ['type' => 'password']);
106
        } else {
107
            $formBuilder->add('current_password',
108
                'Symfony\Component\Form\Extension\Core\Type\PasswordType',
109
                [
110
                    'required' => true,
111
                    'constraints' => new UserPassword(),
112
                    'mapped' => false,
113
                ]);
114
        }
115
116
        $form = $formBuilder->getForm();
117
118
        $form->handleRequest($request);
119
        if ($form->isValid()) {
120
            $data = $form->getData();
121
            $hasChangedPassword = $data->getPassword() == '';
122
            $user->setUsername($data->getUsername());
123
124
            $userManager->updateUser($user);
125
126
            $translator = $this->get('translator');
127
            $this->get('session')->getFlashBag()->add('success',
128
                $translator->trans('Updated username successfully!'));
129
130
            $response = $this->redirect($this->generateUrl('lc_update_username'));
131
            if ($hasChangedPassword) {
132
                $dispatcher = $this->get('event_dispatcher');
133
                $dispatcher->dispatch(FOSUserEvents::CHANGE_PASSWORD_COMPLETED,
134
                    new FilterUserResponseEvent($user, $request, $response));
135
            }
136
137
            return $response;
138
        }
139
140
        return ['form' => $form->createView(), 'emptyPassword' => $emptyPassword];
141
    }
142
143
    /**
144
     * @Route("/facebook/unlink", name="lc_unlink_facebook")
145
     */
146
    public function unlinkFacebookAction()
147
    {
148
        $person = $this->getUser();
149
        $translator = $this->get('translator');
150
        if ($person->hasPassword()) {
151
            $person->setFacebookId(null)
152
                ->setFacebookUsername(null);
153
            $userManager = $this->get('fos_user.user_manager');
154
            $userManager->updateUser($person);
155
156
            $this->get('session')->getFlashBag()->add('success',
157
                $translator->trans("social-networks.unlink.facebook.success"));
158
        } else {
159
            $this->get('session')->getFlashBag()->add('error',
160
                $translator->trans("social-networks.unlink.no-password"));
161
        }
162
163
        return $this->redirect($this->generateUrl('fos_user_profile_edit'));
164
    }
165
166
    /**
167
     * @Route("/twitter/unlink", name="lc_unlink_twitter")
168
     */
169
    public function unlinkTwitterAction()
170
    {
171
        $person = $this->getUser();
172
        $translator = $this->get('translator');
173
        if ($person->hasPassword()) {
174
            $person->setTwitterId(null)
175
                ->setTwitterUsername(null)
176
                ->setTwitterAccessToken(null);
177
            $userManager = $this->get('fos_user.user_manager');
178
            $userManager->updateUser($person);
179
180
            $this->get('session')->getFlashBag()->add('success',
181
                $translator->trans("social-networks.unlink.twitter.success"));
182
        } else {
183
            $this->get('session')->getFlashBag()->add('error',
184
                $translator->trans("social-networks.unlink.no-password"));
185
        }
186
187
        return $this->redirect($this->generateUrl('fos_user_profile_edit'));
188
    }
189
190
    /**
191
     * @Route("/google/unlink", name="lc_unlink_google")
192
     */
193
    public function unlinkGoogleAction()
194
    {
195
        $person = $this->getUser();
196
        $translator = $this->get('translator');
197
        if ($person->hasPassword()) {
198
            $person->setGoogleId(null)
199
                ->setGoogleUsername(null)
200
                ->setGoogleAccessToken(null);
201
            $userManager = $this->get('fos_user.user_manager');
202
            $userManager->updateUser($person);
203
204
            $this->get('session')->getFlashBag()->add('success',
205
                $translator->trans("social-networks.unlink.google.success"));
206
        } else {
207
            $this->get('session')->getFlashBag()->add('error',
208
                $translator->trans("social-networks.unlink.no-password"));
209
        }
210
211
        return $this->redirect($this->generateUrl('fos_user_profile_edit'));
212
    }
213
214
    /**
215
     * @Route("/email/resend-confirmation", name="lc_resend_confirmation_email")
216
     */
217
    public function resendConfirmationEmailAction()
218
    {
219
        $mailer = $this->get('fos_user.mailer');
220
        $translator = $this->get('translator');
221
        $person = $this->getUser();
222
223
        if (is_null($person->getEmailConfirmedAt())) {
224
            if (is_null($person->getConfirmationToken())) {
225
                $tokenGenerator = new TokenGenerator();
226
                $person->setConfirmationToken($tokenGenerator->generateToken());
227
                $userManager = $this->get('fos_user.user_manager');
228
                $userManager->updateUser($person);
229
            }
230
            $mailer->sendConfirmationEmailMessage($person);
231
            $this->get('session')->getFlashBag()->add('success',
232
                $translator->trans("email-confirmation.resent"));
233
        }
234
235
        return $this->redirect($this->generateUrl('fos_user_profile_edit'));
236
    }
237
238
    /**
239
     * @Route("/profile/doc/edit", name="lc_profile_doc_edit")
240
     * @Template()
241
     */
242
    public function docEditAction(Request $request)
243
    {
244
        $user = $this->getUser();
245
        $dispatcher = $this->get('event_dispatcher');
246
247
        $event = new GetResponseUserEvent($user, $request);
248
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
249
250
        $form = $this->createForm('LoginCidadao\CoreBundle\Form\Type\DocFormType',
251
            $user);
252
        $form->handleRequest($request);
253
        if ($form->isValid()) {
254
255
            $event = new FormEvent($form, $request);
256
            $dispatcher->dispatch(ProfileEditListener::PROFILE_DOC_EDIT_SUCCESS,
257
                $event);
258
259
            $userManager = $this->get('fos_user.user_manager');
260
            $userManager->updateUser($user);
261
            $translator = $this->get('translator');
262
            $this->get('session')->getFlashBag()->add('success',
263
                $translator->trans("Documents were successfully changed"));
264
        }
265
        $return = $this->docRgListAction($request);
266
        $return['form'] = $form->createView();
267
268
        return $return;
269
    }
270
271
    /**
272
     * @Route("/profile/doc/rg/remove", name="lc_profile_doc_rg_remove")
273
     * @Template()
274
     */
275
    public function docRgRemoveAction(Request $request)
276
    {
277
        if ($id = $request->get('id')) {
278
            $em = $this->getDoctrine()->getManager();
279
            $rg = $em->getRepository('LoginCidadaoCoreBundle:IdCard')
280
                ->createQueryBuilder('u')
281
                ->where('u.person = :person and u.id = :id')
282
                ->setParameter('person', $this->getUser())
283
                ->setParameter('id', $id)
284
                ->getQuery()
285
                ->getOneOrNullResult();
286
            if ($rg) {
287
                $em->remove($rg);
288
                $em->flush();
289
            }
290
        }
291
        $resp = new Response('<script>rgGrid.getGrid();</script>');
292
293
        return $resp;
294
    }
295
296
    /**
297
     * @Route("/profile/doc/rg/edit", name="lc_profile_doc_rg_edit")
298
     * @Template()
299
     */
300
    public function docRgEditAction(Request $request)
301
    {
302
        $form = $this->createForm(new DocRgFormType());
303
        $rg = null;
304
        if (($id = $request->get('id')) || (($data = $request->get($form->getName()))
305
                && ($id = $data['id']))) {
306
            $rg = $this->getDoctrine()
307
                ->getManager()
308
                ->getRepository('LoginCidadaoCoreBundle:IdCard')->findOneBy([
309
                    'person' => $this->getUser(),
310
                    'id' => $id,
311
                ]);
312
        }
313
        if (!$rg) {
314
            $rg = new IdCard();
315
            $rg->setPerson($this->getUser());
316
        }
317
        $form = $this->createForm(new DocRgFormType(), $rg);
318
        $form->handleRequest($request);
319
        if ($form->isValid()) {
320
            $rgNum = str_split($form->get('value')->getData());
321
            if (($form->get('state')->getData()->getId() == 43) && ($this->checkRGDce($rgNum)
322
                    != $rgNum[0] || $this->checkRGDcd($rgNum) != $rgNum[9])) {
323
                $form->get('value')->addError(new FormError($this->get('translator')->trans('This RG is invalid')));
324
325
                return ['form' => $form->createView()];
326
            }
327
328
            $manager = $this->getDoctrine()->getManager();
329
            $dql = $manager->getRepository('LoginCidadaoCoreBundle:IdCard')
330
                ->createQueryBuilder('u')
331
                ->where('u.person = :person and u.state = :state')
332
                ->setParameter('person', $this->getUser())
333
                ->setParameter('state', $form->get('state')->getData())
334
                ->orderBy('u.id', 'ASC');
335
            if ($rg->getId()) {
336
                $dql->andWhere('u != :rg')->setParameter('rg', $rg);
337
            }
338
            $has = $dql->getQuery()->getResult();
339
            if ($has) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $has of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
340
                $form->get('state')->addError(new FormError($this->get('translator')->trans('You already have an ID registered for this State')));
341
342
                return ['form' => $form->createView()];
343
            }
344
            $manager->persist($rg);
345
            $manager->flush();
346
            $resp = new Response('<script>rgGrid.getGrid();</script>');
347
348
            return $resp;
349
        }
350
351
        return ['form' => $form->createView()];
352
    }
353
354
    private function checkRGDce($rg)
355
    {
356
        $total = ($rg[1] * 2) + ($rg[2] * 3) + ($rg[3] * 4) + ($rg[4] * 5) + ($rg[5]
357
                * 6) + ($rg[6] * 7) + ($rg[7] * 8) + ($rg[8] * 9);
358
        $resto = $total % 11;
359
360
        if ($resto == 0 || $resto == 1) {
361
            return 1;
362
        } else {
363
            return 11 - $resto;
364
        }
365
    }
366
367
    private function checkRGDcd($rg)
368
    {
369
        $n1 = ($rg[8] * 2) % 9;
370
        $n2 = ($rg[6] * 2) % 9;
371
        $n3 = ($rg[4] * 2) % 9;
372
        $n4 = ($rg[2] * 2) % 9;
373
        $n5 = ($rg[0] * 2) % 9;
374
        $total = $n1 + $n2 + $n3 + $n4 + $n5 + $rg[7] + $rg[5] + $rg[3] + $rg[1];
375
376
        if ($rg[8] == 9) {
377
            $total = $total + 9;
378
        }
379
        if ($rg[6] == 9) {
380
            $total = $total + 9;
381
        }
382
        if ($rg[4] == 9) {
383
            $total = $total + 9;
384
        }
385
        if ($rg[2] == 9) {
386
            $total = $total + 9;
387
        }
388
        if ($rg[0] == 9) {
389
            $total = $total + 9;
390
        }
391
392
        $resto = $total % 10;
393
394
        if ($resto == 0) {
395
            return 1;
396
        } else {
397
            return 10 - $resto;
398
        }
399
    }
400
401
    /**
402
     * @Route("/profile/doc/rg/list", name="lc_profile_doc_rg_list")
403
     * @Template()
404
     */
405
    public function docRgListAction(Request $request)
406
    {
407
        $sql = $this->getDoctrine()->getManager()
408
            ->getRepository('LoginCidadaoCoreBundle:IdCard')
409
            ->getGridQuery($this->getUser());
410
411
        $grid = new GridHelper();
412
        $grid->setId('rg-grid');
413
        $grid->setPerPage(4);
414
        $grid->setMaxResult(4);
415
        $grid->setQueryBuilder($sql);
0 ignored issues
show
Deprecated Code introduced by
The function LoginCidadao\CoreBundle\...lper::setQueryBuilder() has been deprecated: since version 1.1.0 ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

415
        /** @scrutinizer ignore-deprecated */ $grid->setQueryBuilder($sql);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
416
        $grid->setInfiniteGrid(true);
417
        $grid->setRoute('lc_profile_doc_rg_list');
418
419
        return ['grid' => $grid->createView($request)];
420
    }
421
422
    /**
423
     * @Route("/profile/badges", name="lc_profile_badges")
424
     * @Template()
425
     */
426
    public function badgesListAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

426
    public function badgesListAction(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
427
    {
428
        /** @var BadgesHandler $badgesHandler */
429
        $badgesHandler = $this->get('badges.handler');
430
431
        $badges = $badgesHandler->getAvailableBadges();
432
        $user = $badgesHandler->evaluate($this->getUser());
433
434
        return ['allBadges' => $badges, 'userBadges' => $user->getBadges()];
435
    }
436
437
    private function removeAll(array $objects)
438
    {
439
        $em = $this->getDoctrine()->getManager();
440
        foreach ($objects as $object) {
441
            $em->remove($object);
442
        }
443
    }
444
445
    private function trans($id, array $parameters = [], $domain = null, $locale = null)
446
    {
447
        /** @var TranslatorInterface $translator */
448
        $translator = $this->get('translator');
449
450
        return $translator->trans($id, $parameters, $domain, $locale);
451
    }
452
453
    private function getTokens($clientId)
454
    {
455
        $user = $this->getUser();
456
        $client = $this->getClient($clientId);
457
        $em = $this->getDoctrine()->getManager();
458
        $accessTokens = $em->getRepository('LoginCidadaoOAuthBundle:AccessToken')->findBy([
459
            'client' => $client,
460
            'user' => $user,
461
        ]);
462
        $refreshTokens = $em->getRepository('LoginCidadaoOAuthBundle:RefreshToken')->findBy([
463
            'client' => $client,
464
            'user' => $user,
465
        ]);
466
467
468
        return array_merge($accessTokens, $refreshTokens);
469
    }
470
471
    private function getClient($clientId)
472
    {
473
        return $this->getDoctrine()->getManager()->getRepository('LoginCidadaoOAuthBundle:Client')->find($clientId);
474
    }
475
476
    private function getAuthorization($clientId)
477
    {
478
        $auth = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Authorization')
479
            ->findOneBy([
480
                'person' => $this->getUser(),
481
                'client' => $this->getClient($clientId),
482
            ]);
483
484
        if (!$auth) {
485
            throw new \InvalidArgumentException($this->trans("Authorization not found."));
486
        }
487
488
        return $auth;
489
    }
490
491
    private function revoke($clientId)
492
    {
493
        try {
494
            if (false === $this->isGranted('ROLE_USER')) {
495
                throw new AccessDeniedException();
496
            }
497
498
            $this->removeAll(array_merge($this->getTokens($clientId), [$this->getAuthorization($clientId)]));
499
            $this->addFlash('success', $this->trans('Authorization successfully revoked.'));
500
501
            $this->getDoctrine()->getManager()->flush();
502
        } catch (AccessDeniedException $e) {
503
            $this->addFlash('error', $this->trans("Access Denied."));
504
        } catch (\Exception $e) {
505
            $this->addFlash('error', $this->trans("Wasn't possible to disable this service."));
506
            $this->addFlash('error', $e->getMessage());
507
        }
508
    }
509
}
510