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