Failed Conditions
Pull Request — master (#262)
by Guilherme
10:25 queued 04:26
created

PersonController::getClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
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/badges", name="lc_profile_badges")
240
     * @Template()
241
     */
242
    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

242
    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...
243
    {
244
        /** @var BadgesHandler $badgesHandler */
245
        $badgesHandler = $this->get('badges.handler');
246
247
        $badges = $badgesHandler->getAvailableBadges();
248
        $user = $badgesHandler->evaluate($this->getUser());
249
250
        return ['allBadges' => $badges, 'userBadges' => $user->getBadges()];
251
    }
252
253
    private function removeAll(array $objects)
254
    {
255
        $em = $this->getDoctrine()->getManager();
256
        foreach ($objects as $object) {
257
            $em->remove($object);
258
        }
259
    }
260
261
    private function trans($id, array $parameters = [], $domain = null, $locale = null)
262
    {
263
        /** @var TranslatorInterface $translator */
264
        $translator = $this->get('translator');
265
266
        return $translator->trans($id, $parameters, $domain, $locale);
267
    }
268
269
    private function getTokens($clientId)
270
    {
271
        $user = $this->getUser();
272
        $client = $this->getClient($clientId);
273
        $em = $this->getDoctrine()->getManager();
274
        $accessTokens = $em->getRepository('LoginCidadaoOAuthBundle:AccessToken')->findBy([
275
            'client' => $client,
276
            'user' => $user,
277
        ]);
278
        $refreshTokens = $em->getRepository('LoginCidadaoOAuthBundle:RefreshToken')->findBy([
279
            'client' => $client,
280
            'user' => $user,
281
        ]);
282
283
284
        return array_merge($accessTokens, $refreshTokens);
285
    }
286
287
    private function getClient($clientId)
288
    {
289
        return $this->getDoctrine()->getManager()->getRepository('LoginCidadaoOAuthBundle:Client')->find($clientId);
290
    }
291
292
    private function getAuthorization($clientId)
293
    {
294
        $auth = $this->getDoctrine()->getRepository('LoginCidadaoCoreBundle:Authorization')
295
            ->findOneBy([
296
                'person' => $this->getUser(),
297
                'client' => $this->getClient($clientId),
298
            ]);
299
300
        if (!$auth) {
301
            throw new \InvalidArgumentException($this->trans("Authorization not found."));
302
        }
303
304
        return $auth;
305
    }
306
307
    private function revoke($clientId)
308
    {
309
        try {
310
            if (false === $this->isGranted('ROLE_USER')) {
311
                throw new AccessDeniedException();
312
            }
313
314
            $this->removeAll(array_merge($this->getTokens($clientId), [$this->getAuthorization($clientId)]));
315
            $this->addFlash('success', $this->trans('Authorization successfully revoked.'));
316
317
            $this->getDoctrine()->getManager()->flush();
318
        } catch (AccessDeniedException $e) {
319
            $this->addFlash('error', $this->trans("Access Denied."));
320
        } catch (\Exception $e) {
321
            $this->addFlash('error', $this->trans("Wasn't possible to disable this service."));
322
            $this->addFlash('error', $e->getMessage());
323
        }
324
    }
325
}
326