Completed
Push — master ( 22f213...24f6ce )
by Guilherme
17:25
created

PersonController::resendConfirmationEmailAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 14
nc 3
nop 0
dl 0
loc 20
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()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
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(array(
309
                    'person' => $this->getUser(),
310
                    'id' => $id,
311
                ));
312
        }
313
        if (!$rg) {
314
            $rg = new IdCard();
315
            $rg->setPerson($this->getUser());
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<LoginCidadao\Core...\Model\PersonInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
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 array('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) {
340
                $form->get('state')->addError(new FormError($this->get('translator')->trans('You already have an ID registered for this State')));
341
342
                return array('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 array('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 method LoginCidadao\CoreBundle\...lper::setQueryBuilder() has been deprecated with message: since version 1.1.0

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

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

Loading history...
416
        $grid->setInfiniteGrid(true);
417
        $grid->setRoute('lc_profile_doc_rg_list');
418
419
        return array('grid' => $grid->createView($request));
420
    }
421
422
    /**
423
     * @Route("/register/prefilled", name="lc_prefilled_registration")
424
     */
425
    public function preFilledRegistrationAction(Request $request)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
426
    {
427
        if (null !== $this->getUser()) {
428
            return $this->get('templating')->renderResponse('LoginCidadaoCoreBundle:Person:registration/errorAlreadyLoggedin.html.twig');
429
        }
430
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
431
        $formFactory = $this->get('fos_user.registration.form.factory');
432
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
433
        $userManager = $this->get('fos_user.user_manager');
434
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
435
        $dispatcher = $this->get('event_dispatcher');
436
437
        /** @var PersonInterface $user */
438
        $user = $userManager->createUser();
439
        $user->setEnabled(true);
440
441
        $fullName = $request->get('full_name');
442
443
        if (!is_null($fullName)) {
444
            $name = explode(' ', trim($fullName), 2);
445
            $user->setFirstName($name[0]);
446
            $user->setSurname($name[1]);
447
        }
448
        $user->setEmail($request->get('email'));
449
        $user->setMobile($request->get('mobile'));
450
451
        $event = new GetResponseUserEvent($user, $request);
452
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
453
454
        if (null !== $event->getResponse()) {
455
            return $event->getResponse();
456
        }
457
458
        $form = $formFactory->createForm();
459
460
        $form->add('firstName', 'text',
461
            array('required' => false, 'label' => 'form.firstName', 'translation_domain' => 'FOSUserBundle'))
462
            ->add('surname', 'text',
463
                array('required' => false, 'label' => 'form.surname', 'translation_domain' => 'FOSUserBundle'));
464
465
        $form->setData($user);
466
467
        if ('POST' === $request->getMethod()) {
468
            $form->bind($request);
469
470
            if ($form->isValid()) {
471
                $event = new FormEvent($form, $request);
472
                $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS,
473
                    $event);
474
475
                $userManager->updateUser($user);
476
477
                if (null === $response = $event->getResponse()) {
478
                    $url = $this->get('router')->generate('fos_user_registration_confirmed');
479
                    $response = new RedirectResponse($url);
480
                }
481
482
                $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED,
483
                    new FilterUserResponseEvent($user, $request, $response));
484
485
                return $response;
486
            }
487
        }
488
489
        return $this->get('templating')->renderResponse('LoginCidadaoCoreBundle:Person:registration/preFilledRegistration.html.twig',
490
            array(
491
                'form' => $form->createView(),
492
                'actionUrl' => 'lc_prefilled_registration',
493
            ));
494
    }
495
496
    /**
497
     * @Route("/profile/badges", name="lc_profile_badges")
498
     * @Template()
499
     */
500
    public function badgesListAction(Request $request)
501
    {
502
        /** @var BadgesHandler $badgesHandler */
503
        $badgesHandler = $this->get('badges.handler');
504
505
        $badges = $badgesHandler->getAvailableBadges();
506
        $user = $badgesHandler->evaluate($this->getUser());
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<LoginCidadao\Core...\Model\PersonInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
507
508
        return array('allBadges' => $badges, 'userBadges' => $user->getBadges());
509
    }
510
511
    private function removeAll(array $objects)
512
    {
513
        $em = $this->getDoctrine()->getManager();
514
        foreach ($objects as $object) {
515
            $em->remove($object);
516
        }
517
    }
518
519
    private function trans($id, array $parameters = array(), $domain = null, $locale = null)
520
    {
521
        /** @var TranslatorInterface $translator */
522
        $translator = $this->get('translator');
523
524
        return $translator->trans($id, $parameters, $domain, $locale);
525
    }
526
527
    private function getTokens($clientId)
528
    {
529
        $user = $this->getUser();
530
        $client = $this->getClient($clientId);
531
        $em = $this->getDoctrine()->getManager();
532
        $accessTokens = $em->getRepository('LoginCidadaoOAuthBundle:AccessToken')->findBy([
533
            'client' => $client,
534
            'user' => $user,
535
        ]);
536
        $refreshTokens = $em->getRepository('LoginCidadaoOAuthBundle:RefreshToken')->findBy([
537
            'client' => $client,
538
            'user' => $user,
539
        ]);
540
541
542
        return array_merge($accessTokens, $refreshTokens);
543
    }
544
545
    private function getClient($clientId)
546
    {
547
        return $this->getDoctrine()->getManager()->getRepository('LoginCidadaoOAuthBundle:Client')->find($clientId);
548
    }
549
550
    private function getAuthorization($clientId)
551
    {
552
        $auth = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Authorization')
553
            ->findBy([
554
                'person' => $this->getUser(),
555
                'client' => $this->getClient($clientId),
556
            ]);
557
558
        if (!$auth) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $auth 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...
559
            throw new \InvalidArgumentException($this->trans("Authorization not found."));
560
        }
561
562
        return $auth;
563
    }
564
565
    private function revoke($clientId)
566
    {
567
        try {
568
            if (false === $this->isGranted('ROLE_USER')) {
569
                throw new AccessDeniedException();
570
            }
571
572
            $this->removeAll(array_merge($this->getTokens($clientId), [$this->getAuthorization($clientId)]));
573
            $this->addFlash('success', $this->trans('Authorization successfully revoked.'));
574
575
            $this->getDoctrine()->getManager()->flush();
576
        } catch (AccessDeniedException $e) {
577
            $this->addFlash('error', $this->trans("Access Denied."));
578
        } catch (\Exception $e) {
579
            $this->addFlash('error', $this->trans("Wasn't possible to disable this service."));
580
            $this->addFlash('error', $e->getMessage());
581
        }
582
    }
583
}
584