]> Raphaël G. Git Repositories - airbundle/blob - Controller/UserController.php
Version 0.5.0
[airbundle] / Controller / UserController.php
1 <?php declare(strict_types=1);
2
3 /*
4 * This file is part of the Rapsys AirBundle package.
5 *
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Rapsys\AirBundle\Controller;
13
14 use Doctrine\ORM\EntityManagerInterface;
15 use Doctrine\Persistence\ManagerRegistry;
16
17 use Google\Client;
18
19 use Psr\Container\ContainerInterface;
20 use Psr\Log\LoggerInterface;
21
22 use Symfony\Bundle\SecurityBundle\Security;
23 use Symfony\Component\Form\FormFactoryInterface;
24 use Symfony\Component\HttpFoundation\Request;
25 use Symfony\Component\HttpFoundation\RequestStack;
26 use Symfony\Component\HttpFoundation\Response;
27 use Symfony\Component\Mailer\MailerInterface;
28 use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
29 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
30 use Symfony\Component\Routing\RouterInterface;
31 use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
32 use Symfony\Contracts\Cache\CacheInterface;
33 use Symfony\Contracts\Cache\ItemInterface;
34 use Symfony\Contracts\Translation\TranslatorInterface;
35
36 use Rapsys\UserBundle\Controller\UserController as BaseUserController;
37
38 use Rapsys\AirBundle\Entity\Dance;
39 use Rapsys\AirBundle\Entity\GoogleCalendar;
40 use Rapsys\AirBundle\Entity\GoogleToken;
41 use Rapsys\AirBundle\Entity\User;
42
43 use Rapsys\PackBundle\Util\SluggerUtil;
44
45 use Twig\Environment;
46
47 /**
48 * {@inheritdoc}
49 */
50 class UserController extends BaseUserController {
51 /**
52 * {@inheritdoc}
53 *
54 * @param CacheInterface $cache The cache instance
55 * @param AuthorizationCheckerInterface $checker The checker instance
56 * @param ContainerInterface $container The container instance
57 * @param ManagerRegistry $doctrine The doctrine instance
58 * @param FormFactoryInterface $factory The factory instance
59 * @param UserPasswordHasherInterface $hasher The password hasher instance
60 * @param LoggerInterface $logger The logger instance
61 * @param MailerInterface $mailer The mailer instance
62 * @param EntityManagerInterface $manager The manager instance
63 * @param RouterInterface $router The router instance
64 * @param Security $security The security instance
65 * @param SluggerUtil $slugger The slugger instance
66 * @param RequestStack $stack The stack instance
67 * @param TranslatorInterface $translator The translator instance
68 * @param Environment $twig The twig environment instance
69 * @param Client $google The google client instance
70 * @param integer $limit The page limit
71 */
72 public function __construct(protected CacheInterface $cache, protected AuthorizationCheckerInterface $checker, protected ContainerInterface $container, protected ManagerRegistry $doctrine, protected FormFactoryInterface $factory, protected UserPasswordHasherInterface $hasher, protected LoggerInterface $logger, protected MailerInterface $mailer, protected EntityManagerInterface $manager, protected RouterInterface $router, protected Security $security, protected SluggerUtil $slugger, protected RequestStack $stack, protected TranslatorInterface $translator, protected Environment $twig, protected Client $google, protected int $limit = 5) {
73 //Call parent constructor
74 parent::__construct($this->cache, $this->checker, $this->container, $this->doctrine, $this->factory, $this->hasher, $this->logger, $this->mailer, $this->manager, $this->router, $this->security, $this->slugger, $this->stack, $this->translator, $this->twig, $this->limit);
75
76 //Replace google client redirect uri
77 $this->google->setRedirectUri($this->router->generate($this->google->getRedirectUri(), [], UrlGeneratorInterface::ABSOLUTE_URL));
78 }
79
80 /**
81 * {@inheritdoc}
82 */
83 public function edit(Request $request, string $hash, string $mail): Response {
84 //With invalid hash
85 if ($hash != $this->slugger->hash($mail)) {
86 //Throw bad request
87 throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash]));
88 }
89
90 //Get mail
91 $mail = $this->slugger->unshort($smail = $mail);
92
93 //With existing subscriber
94 if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) {
95 //Throw not found
96 //XXX: prevent slugger reverse engineering by not displaying decoded mail
97 throw $this->createNotFoundException($this->translator->trans('Unable to find account %mail%', ['%mail%' => $smail]));
98 }
99
100 //Prevent access when not admin, user is not guest and not currently logged user
101 if (!$this->checker->isGranted('ROLE_ADMIN') && $user != $this->security->getUser() || !$this->checker->isGranted('IS_AUTHENTICATED_FULLY')) {
102 //Throw access denied
103 //XXX: prevent slugger reverse engineering by not displaying decoded mail
104 throw $this->createAccessDeniedException($this->translator->trans('Unable to access user: %mail%', ['%mail%' => $smail]));
105 }
106
107 //Create the RegisterType form and give the proper parameters
108 $edit = $this->factory->create($this->config['edit']['view']['edit'], $user, [
109 //Set action to register route name and context
110 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']),
111 //Set civility class
112 'civility_class' => $this->config['class']['civility'],
113 //Set civility default
114 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']),
115 //Set country class
116 'country_class' => $this->config['class']['country'],
117 //Set country default
118 'country_default' => $this->doctrine->getRepository($this->config['class']['country'])->findOneByTitle($this->config['default']['country']),
119 //Set country favorites
120 'country_favorites' => $this->doctrine->getRepository($this->config['class']['country'])->findByTitle($this->config['default']['country_favorites']),
121 //Set dance
122 'dance' => $this->checker->isGranted('ROLE_ADMIN'),
123 //Set dance choices
124 'dance_choices' => $danceChoices = $this->doctrine->getRepository($this->config['class']['dance'])->findChoicesAsArray(),
125 //Set dance default
126 #'dance_default' => /*$this->doctrine->getRepository($this->config['class']['dance'])->findOneByNameType($this->config['default']['dance'])*/null,
127 //Set dance favorites
128 'dance_favorites' => $this->doctrine->getRepository($this->config['class']['dance'])->findIdByNameTypeAsArray($this->config['default']['dance_favorites']),
129 //Set subscription
130 'subscription' => $this->checker->isGranted('ROLE_ADMIN'),
131 //Set subscription choices
132 'subscription_choices' => $subscriptionChoices = $this->doctrine->getRepository($this->config['class']['user'])->findChoicesAsArray(),
133 //Set subscription default
134 #'subscription_default' => /*$this->doctrine->getRepository($this->config['class']['user'])->findOneByPseudonym($this->config['default']['subscription'])*/null,
135 //Set subscription favorites
136 'subscription_favorites' => $this->doctrine->getRepository($this->config['class']['user'])->findIdByPseudonymAsArray($this->config['default']['subscription_favorites']),
137 //Disable mail
138 'mail' => $this->checker->isGranted('ROLE_ADMIN'),
139 //Disable pseudonym
140 'pseudonym' => $this->checker->isGranted('ROLE_GUEST'),
141 //Disable password
142 'password' => false,
143 //Set method
144 'method' => 'POST'
145 ]+$this->config['edit']['field']);
146
147 //With admin role
148 if ($this->checker->isGranted('ROLE_ADMIN')) {
149 //Create the ResetType form and give the proper parameters
150 $reset = $this->factory->create($this->config['edit']['view']['reset'], $user, [
151 //Set action to register route name and context
152 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']),
153 //Disable mail
154 'mail' => false,
155 //Set method
156 'method' => 'POST'
157 ]);
158
159 //With post method
160 if ($request->isMethod('POST')) {
161 //Refill the fields in case the form is not valid.
162 $reset->handleRequest($request);
163
164 //With reset submitted and valid
165 if ($reset->isSubmitted() && $reset->isValid()) {
166 //Set data
167 $data = $reset->getData();
168
169 //Set password
170 $data->setPassword($this->hasher->hashPassword($data, $data->getPassword()));
171
172 //Queue user password save
173 $this->manager->persist($data);
174
175 //Flush to get the ids
176 $this->manager->flush();
177
178 //Add notice
179 $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail]));
180
181 //Redirect to cleanup the form
182 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']);
183 }
184 }
185
186 //Add reset view
187 $this->config['edit']['view']['context']['reset'] = $reset->createView();
188
189 //Add google calendar array
190 $this->config['edit']['view']['context']['calendar'] = [
191 //Form by mail
192 'form' => [],
193 //Uri to link account
194 'link' => null,
195 //Logo
196 'logo' => [
197 'png' => '@RapsysAir/png/calendar.png',
198 'svg' => '@RapsysAir/svg/calendar.svg'
199 ]
200 ];
201
202 //Set login hint
203 $this->google->setLoginHint($user->getMail());
204
205 //With user tokens
206 if (!($googleTokens = $user->getGoogleTokens())->isEmpty()) {
207 //Iterate on each google token
208 //XXX: either we finish with a valid token set or a logic exception after token removal
209 foreach($googleTokens as $googleToken) {
210 //Clear client cache before changing access token
211 //TODO: set a per token cache ?
212 $this->google->getCache()->clear();
213
214 //Set access token
215 $this->google->setAccessToken(
216 [
217 'access_token' => $googleToken->getAccess(),
218 'refresh_token' => $googleToken->getRefresh(),
219 'created' => $googleToken->getCreated()->getTimestamp(),
220 'expires_in' => $googleToken->getExpired()->getTimestamp() - (new \DateTime('now'))->getTimestamp(),
221 ]
222 );
223
224 //With expired token
225 if ($this->google->isAccessTokenExpired()) {
226 //Refresh token
227 if (($refresh = $this->google->getRefreshToken()) && ($token = $this->google->fetchAccessTokenWithRefreshToken($refresh)) && empty($token['error'])) {
228 //Set access token
229 $googleToken->setAccess($token['access_token']);
230
231 //Set expires
232 $googleToken->setExpired(new \DateTime('+'.$token['expires_in'].' second'));
233
234 //Set refresh
235 $googleToken->setRefresh($token['refresh_token']);
236
237 //Queue google token save
238 $this->manager->persist($googleToken);
239
240 //Flush to get the ids
241 $this->manager->flush();
242 //Refresh failed
243 } else {
244 //Add error in flash message
245 $this->addFlash(
246 'error',
247 $this->translator->trans(
248 empty($token['error'])?'Unable to refresh token':'Unable to refresh token: %error%',
249 empty($token['error'])?[]:['%error%' => str_replace('_', ' ', $token['error'])]
250 )
251 );
252
253 //Set calendar mails
254 $cmails = [];
255
256 //Iterate on each google token calendars
257 foreach($googleToken->getGoogleCalendars() as $googleCalendar) {
258 //Add calendar mail
259 $cmails[] = $googleCalendar->getMail();
260
261 //Remove google token calendar
262 $this->manager->remove($googleCalendar);
263 }
264
265 //Log unlinked google token infos
266 $this->logger->emergency(
267 $this->translator->trans(
268 'expired: mail=%mail% gmail=%gmail% cmails=%cmails% locale=%locale%',
269 [
270 '%mail%' => $googleToken->getUser()->getMail(),
271 '%gmail%' => $googleToken->getMail(),
272 '%cmails' => implode(',', $cmails),
273 '%locale%' => $request->getLocale()
274 ]
275 )
276 );
277
278 //Remove google token
279 $this->manager->remove($googleToken);
280
281 //Flush to delete it
282 $this->manager->flush();
283
284 //TODO: warn user by mail ?
285
286 //Skip to next token
287 continue;
288 }
289 }
290
291 //XXX: TODO: remove DEBUG
292 #$this->cache->delete('user.edit.calendar.'.$this->slugger->short($googleToken->getMail()));
293
294 //Retrieve calendar
295 try {
296 //Get calendars
297 $calendars = $this->cache->get(
298 //Set key to user.edit.$mail
299 ($calendarKey = 'user.edit.calendar.'.($googleShortMail = $this->slugger->short($googleMail = $googleToken->getMail()))),
300 //Fetch mail calendar list
301 function (ItemInterface $item): array {
302 //Expire after 1h
303 $item->expiresAfter(3600);
304
305 //Get google calendar service
306 $service = new \Google\Service\Calendar($this->google);
307
308 //Init calendars
309 $calendars = [];
310
311 //Init counter
312 $count = 0;
313
314 //Set page token
315 $pageToken = null;
316
317 //Iterate until next page token is null
318 do {
319 //Get token calendar list
320 //XXX: require permission to read and write events
321 $calendarList = $service->calendarList->listCalendarList(['pageToken' => $pageToken, 'minAccessRole' => 'writer', 'showHidden' => true]);
322
323 //Iterate on items
324 foreach($calendarList->getItems() as $calendarItem) {
325 //With primary calendar
326 if ($calendarItem->getPrimary()) {
327 //Add primary calendar
328 //XXX: use primary as key as described in google api documentation
329 $calendars = ['primary' => $this->translator->trans('Primary') /*$calendarItem->getSummary()*/] + $calendars;
330 //With secondary calendar
331 } else {
332 //Add secondary calendar
333 //XXX: Append counter to make sure summary is unique for later array_flip call
334 $calendars += [$calendarItem->getId() => $calendarItem->getSummary().' ('.++$count.')'];
335 }
336 }
337 } while ($pageToken = $calendarList->getNextPageToken());
338
339 //Cache calendars
340 return $calendars;
341 }
342 );
343 //Catch exception
344 } catch(\Google\Service\Exception $e) {
345 //With 401 or code
346 //XXX: see https://cloud.google.com/apis/design/errors
347 if ($e->getCode() == 401 || $e->getCode() == 403) {
348 //Add error in flash message
349 $this->addFlash(
350 'error',
351 $this->translator->trans(
352 'Unable to list calendars: %error%',
353 ['%error%' => $e->getMessage()]
354 )
355 );
356
357 //Set calendar mails
358 $cmails = [];
359
360 //Iterate on each google token calendars
361 foreach($googleToken->getGoogleCalendars() as $googleCalendar) {
362 //Add calendar mail
363 $cmails[] = $googleCalendar->getMail();
364
365 //Remove google token calendar
366 $this->manager->remove($googleCalendar);
367 }
368
369 //Log unlinked google token infos
370 $this->logger->emergency(
371 $this->translator->trans(
372 'denied: mail=%mail% gmail=%gmail% cmails=%cmails% locale=%locale%',
373 [
374 '%mail%' => $googleToken->getUser()->getMail(),
375 '%gmail%' => $googleToken->getMail(),
376 '%cmails' => implode(',', $cmails),
377 '%locale%' => $request->getLocale()
378 ]
379 )
380 );
381
382 //Remove google token
383 $this->manager->remove($googleToken);
384
385 //Flush to delete it
386 $this->manager->flush();
387
388 //TODO: warn user by mail ?
389
390 //Skip to next token
391 continue;
392 }
393
394 //Throw error
395 throw new \LogicException('Calendar list failed', 0, $e);
396 }
397
398 //Set formData array
399 $formData = ['calendar' => []];
400
401 //With google calendars
402 if (!($googleCalendars = $googleToken->getGoogleCalendars())->isEmpty()) {
403 //Iterate on each google calendars
404 foreach($googleCalendars as $googleCalendar) {
405 //With existing google calendar
406 if (isset($calendars[$googleCalendar->getMail()])) {
407 //Add google calendar to form data
408 $formData['calendar'][] = $googleCalendar->getMail();
409 } else {
410 //Remove google calendar from database
411 $this->manager->remove($googleCalendar);
412
413 //Flush to persist ids
414 $this->manager->flush();
415 }
416 }
417 }
418
419 //TODO: add feature for alerts (-30min/-1h) ?
420 //TODO: [Direct link to calendar ?][Direct link to calendar settings ?][Alerts][Remove]
421
422 //Create the CalendarType form and give the proper parameters
423 $form = $this->factory->createNamed('calendar_'.$googleShortMail, 'Rapsys\AirBundle\Form\CalendarType', $formData, [
424 //Set action to register route name and context
425 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']),
426 //Set calendar choices
427 //XXX: unique calendar summary required by choice widget is guaranteed by appending ' (x)' to secondary calendars earlier
428 'calendar_choices' => array_flip($calendars),
429 //Set method
430 'method' => 'POST'
431 ]);
432
433 //With post method
434 if ($request->isMethod('POST')) {
435 //Refill the fields in case the form is not valid.
436 $form->handleRequest($request);
437
438 //With reset submitted and valid
439 if ($form->isSubmitted() && $form->isValid()) {
440 //Set data
441 $data = $form->getData();
442
443 //Refresh button
444 if (($clicked = $form->getClickedButton()->getName()) == 'refresh') {
445 //Remove calendar key
446 $this->cache->delete($calendarKey);
447
448 //Add notice
449 $this->addFlash('notice', $this->translator->trans('Account %mail% calendars updated', ['%mail%' => $googleMail]));
450 //Add button
451 } elseif ($clicked == 'add') {
452 //Get google calendar service
453 $service = new \Google\Service\Calendar($this->google);
454
455 //Add calendar
456 try {
457 //Instantiate calendar
458 $calendar = new \Google\Service\Calendar\Calendar(
459 [
460 'summary' => $this->translator->trans($this->config['context']['site']['title']),
461 'timeZone' => date_default_timezone_get()
462 ]
463 );
464
465 //Insert calendar
466 $service->calendars->insert($calendar);
467 //Catch exception
468 } catch(\Google\Service\Exception $e) {
469 //Throw error
470 throw new \LogicException('Calendar insert failed', 0, $e);
471 }
472
473 //Remove calendar key
474 $this->cache->delete($calendarKey);
475
476 //Add notice
477 $this->addFlash('notice', $this->translator->trans('Account %mail% calendar added', ['%mail%' => $googleMail]));
478 //Delete button
479 } elseif ($clicked == 'delete') {
480 //Get google calendar service
481 $service = new \Google\Service\Calendar($this->google);
482
483 //Remove calendar
484 try {
485 //Set site title
486 $siteTitle = $this->translator->trans($this->config['context']['site']['title']);
487
488 //Iterate on calendars
489 foreach($calendars as $calendarId => $calendarSummary) {
490 //With calendar matching site title
491 if (substr($calendarSummary, 0, strlen($siteTitle)) == $siteTitle) {
492 //Delete the calendar
493 $service->calendars->delete($calendarId);
494 }
495 }
496 //Catch exception
497 } catch(\Google\Service\Exception $e) {
498 //Throw error
499 throw new \LogicException('Calendar delete failed', 0, $e);
500 }
501
502 //Remove calendar key
503 $this->cache->delete($calendarKey);
504
505 //Add notice
506 $this->addFlash('notice', $this->translator->trans('Account %mail% calendars deleted', ['%mail%' => $googleMail]));
507 //Unlink button
508 } elseif ($clicked == 'unlink') {
509 //Iterate on each google calendars
510 foreach($googleCalendars as $googleCalendar) {
511 //Remove google calendar from database
512 $this->manager->remove($googleCalendar);
513 }
514
515 //Remove google token from database
516 $this->manager->remove($googleToken);
517
518 //Flush to persist
519 $this->manager->flush();
520
521 //Revoke access token
522 $this->google->revokeToken($googleToken->getAccess());
523
524 //With refresh token
525 if ($refresh = $googleToken->getRefresh()) {
526 //Revoke refresh token
527 $this->google->revokeToken($googleToken->getRefresh());
528 }
529
530 //Remove calendar key
531 $this->cache->delete($calendarKey);
532
533 //Add notice
534 $this->addFlash('notice', $this->translator->trans('Account %mail% calendars unlinked', ['%mail%' => $googleMail]));
535 //Submit button
536 } else {
537 //Flipped calendar data
538 $dataCalendarFlip = array_flip($data['calendar']);
539
540 //Iterate on each google calendars
541 foreach($googleCalendars as $googleCalendar) {
542 //Without calendar in flipped data
543 if (!isset($dataCalendarFlip[$googleCalendarMail = $googleCalendar->getMail()])) {
544 //Remove google calendar from database
545 $this->manager->remove($googleCalendar);
546 //With calendar in flipped data
547 } else {
548 //Remove google calendar from calendar data
549 unset($data['calendar'][$dataCalendarFlip[$googleCalendarMail]]);
550 }
551 }
552
553 //Iterate on remaining calendar data
554 foreach($data['calendar'] as $googleCalendarMail) {
555 //Create new google calendar
556 //XXX: remove trailing ' (x)' from summary
557 $googleCalendar = new GoogleCalendar($googleToken, $googleCalendarMail, preg_replace('/ \([0-9]\)$/', '', $calendars[$googleCalendarMail]));
558
559 //Queue google calendar save
560 $this->manager->persist($googleCalendar);
561 }
562
563 //Flush to persist ids
564 $this->manager->flush();
565
566 //Add notice
567 $this->addFlash('notice', $this->translator->trans('Account %mail% calendars updated', ['%mail%' => $googleMail]));
568 }
569
570 //Redirect to cleanup the form
571 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']);
572 }
573 }
574
575 //Add form view
576 $this->config['edit']['view']['context']['calendar']['form'][$googleToken->getMail()] = $form->createView();
577 }
578 }
579
580 //Add google calendar auth url
581 $this->config['edit']['view']['context']['calendar']['link'] = $this->google->createAuthUrl();
582 }
583
584 //With post method
585 if ($request->isMethod('POST')) {
586 //Refill the fields in case the form is not valid.
587 $edit->handleRequest($request);
588
589 //With edit submitted and valid
590 if ($edit->isSubmitted() && $edit->isValid()) {
591 //Set data
592 $data = $edit->getData();
593
594 //Queue user save
595 $this->manager->persist($data);
596
597 //Try saving in database
598 try {
599 //Flush to get the ids
600 $this->manager->flush();
601
602 //Add notice
603 //XXX: get mail from data as it may change
604 $this->addFlash('notice', $this->translator->trans('Account %mail% updated', ['%mail%' => $mail = $data->getMail()]));
605
606 //Redirect to cleanup the form
607 return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']);
608 //Catch double slug or mail
609 } catch (UniqueConstraintViolationException $e) {
610 //Add error message mail already exists
611 $this->addFlash('error', $this->translator->trans('Account %mail% already exists', ['%mail%' => $data->getMail()]));
612 }
613 }
614 //Without admin role
615 //XXX: prefer a reset on login to force user unspam action
616 } elseif (!$this->checker->isGranted('ROLE_ADMIN')) {
617 //Add notice
618 $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure'));
619 }
620
621 //Render view
622 return $this->render(
623 //Template
624 $this->config['edit']['view']['name'],
625 //Context
626 ['edit' => $edit->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['edit']['view']['context']
627 );
628 }
629
630 /**
631 * Handle google callback
632 *
633 * @param Request $request The request
634 * @return Response The response
635 */
636 public function googleCallback(Request $request): Response {
637 //Without code
638 if (empty($code = $request->query->get('code', ''))) {
639 throw new \InvalidArgumentException('Query parameter code is empty');
640 }
641
642 //Without user
643 if (empty($user = $this->security->getUser())) {
644 throw new \LogicException('User is empty');
645 }
646
647 //Set google client login hint
648 $this->google->setLoginHint($user->getMail());
649
650 //Set google client scopes
651 $googleScopes = [\Google\Service\Calendar::CALENDAR_EVENTS, \Google\Service\Calendar::CALENDAR, \Google\Service\Oauth2::USERINFO_EMAIL];
652
653 //Protect to extract failure
654 try {
655 //Authenticate with code
656 if (!empty($token = $this->google->authenticate($code))) {
657 //With error
658 if (!empty($token['error'])) {
659 throw new \LogicException('Client authenticate failed: '.str_replace('_', ' ', $token['error']));
660 //Without refresh token
661 } elseif (empty($token['refresh_token'])) {
662 throw new \LogicException('Refresh token is empty');
663 //Without expires in
664 } elseif (empty($token['expires_in'])) {
665 throw new \LogicException('Expires in is empty');
666 //Without scope
667 } elseif (empty($token['scope'])) {
668 throw new \LogicException('Scope in is empty');
669 //Without valid scope
670 } elseif (array_intersect($googleScopes, explode(' ', $token['scope'])) != $googleScopes) {
671 throw new \LogicException('Scope in is not valid');
672 }
673
674 //Get Oauth2 object
675 $oauth2 = new \Google\Service\Oauth2($this->google);
676
677 //Protect user info get call
678 try {
679 //Retrieve user info
680 $userInfo = $oauth2->userinfo->get();
681 //Catch exception
682 } catch(\Google\Service\Exception $e) {
683 //Throw error
684 throw new \LogicException('Userinfo get failed', 0, $e);
685 }
686
687 //With existing token
688 if (
689 //If available retrieve google token with matching mail
690 $googleToken = array_reduce(
691 $user->getGoogleTokens()->getValues(),
692 function ($c, $i) use ($userInfo) {
693 if ($i->getMail() == $userInfo['email']) {
694 return $i;
695 }
696 }
697 )
698 ) {
699 //Set mail
700 //XXX: TODO: should already be set and not change, remove ?
701 //XXX: TODO: store picture as well ?
702 $googleToken->setMail($userInfo['email']);
703
704 //Set access token
705 $googleToken->setAccess($token['access_token']);
706
707 //Set expires
708 $googleToken->setExpired(new \DateTime('+'.$token['expires_in'].' second'));
709
710 //Set refresh
711 $googleToken->setRefresh($token['refresh_token']);
712 } else {
713 //Create new token
714 //XXX: TODO: store picture as well ?
715 $googleToken = new GoogleToken($user, $userInfo['email'], $token['access_token'], new \DateTime('+'.$token['expires_in'].' second'), $token['refresh_token']);
716 }
717
718 //Queue google token save
719 $this->manager->persist($googleToken);
720
721 //Flush to get the ids
722 $this->manager->flush();
723
724 //Add notice
725 $this->addFlash('notice', $this->translator->trans('Account %mail% google token updated', ['%mail%' => $user->getMail()]));
726 //With failed authenticate
727 } else {
728 throw new \LogicException('Client authenticate failed');
729 }
730 //Catch exception
731 } catch(\Exception $e) {
732 //Add notice
733 $this->addFlash('error', $this->translator->trans('Account %mail% google token rejected: %error%', ['%mail%' => $user->getMail(), '%error%' => $e->getMessage()]));
734 }
735
736 //Redirect to user
737 return $this->redirectToRoute('rapsysuser_edit', ['mail' => $short = $this->slugger->short($user->getMail()), 'hash' => $this->slugger->hash($short)]);
738 }
739 }