X-Git-Url: https://git.rapsys.eu/airbundle/blobdiff_plain/14c0138bf34a20695b23aaad2e4a5d4902e7bb1e..aecd79b0af016492323465e0526dbbbd94178976:/Controller/UserController.php?ds=inline diff --git a/Controller/UserController.php b/Controller/UserController.php index 963f538..bd28a54 100644 --- a/Controller/UserController.php +++ b/Controller/UserController.php @@ -1,308 +1,645 @@ - + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ namespace Rapsys\AirBundle\Controller; +use Symfony\Contracts\Cache\ItemInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Routing\RequestContext; -use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; - -use Rapsys\AirBundle\Entity\Civility; -use Rapsys\AirBundle\Entity\Location; -use Rapsys\AirBundle\Entity\Session; -use Rapsys\AirBundle\Entity\Slot; -use Rapsys\AirBundle\Entity\Snippet; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; + +use Rapsys\UserBundle\Controller\UserController as BaseUserController; + +use Rapsys\AirBundle\Entity\Dance; +use Rapsys\AirBundle\Entity\GoogleCalendar; +use Rapsys\AirBundle\Entity\GoogleToken; use Rapsys\AirBundle\Entity\User; -class UserController extends DefaultController { +/** + * {@inheritdoc} + */ +class UserController extends BaseUserController { /** - * List all users - * - * @desc Display all user with a group listed as users - * - * @param Request $request The request instance - * - * @return Response The rendered view + * Set google client scopes */ - public function index(Request $request): Response { - //Fetch doctrine - $doctrine = $this->getDoctrine(); - - //Set section - $section = $this->translator->trans('Libre Air users'); - - //Set description - $this->context['description'] = $this->translator->trans('Libre Air user list'); - - //Set keywords - $this->context['keywords'] = [ - $this->translator->trans('users'), - $this->translator->trans('user list'), - $this->translator->trans('listing'), - $this->translator->trans('Libre Air') - ]; - - //Set title - $title = $this->translator->trans($this->config['site']['title']).' - '.$section; - - //Fetch users - $users = $doctrine->getRepository(User::class)->findUserGroupedByTranslatedGroup($this->translator); - - //Compute period - $period = new \DatePeriod( - //Start from first monday of week - new \DateTime('Monday this week'), - //Iterate on each day - new \DateInterval('P1D'), - //End with next sunday and 4 weeks - new \DateTime( - $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week' - ) - ); - - //Without admin role - if (!$this->isGranted('ROLE_ADMIN')) { - //Remove users - unset($users[$this->translator->trans('User')]); - } - - //Fetch locations - //XXX: we want to display all active locations anyway - $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period); - - //Render the view - return $this->render('@RapsysAir/user/index.html.twig', ['title' => $title, 'section' => $section, 'users' => $users, 'locations' => $locations]+$this->context); - } + const googleScopes = [\Google\Service\Calendar::CALENDAR_EVENTS, \Google\Service\Calendar::CALENDAR, \Google\Service\Oauth2::USERINFO_EMAIL]; /** - * List all sessions for the user - * - * @desc Display all sessions for the user with an application or login form - * - * @param Request $request The request instance - * @param int $id The user id - * - * @return Response The rendered view + * {@inheritdoc} */ - public function view(Request $request, $id): Response { - //Fetch doctrine - $doctrine = $this->getDoctrine(); - - //Fetch user - if (empty($user = $doctrine->getRepository(User::class)->findOneById($id))) { - throw $this->createNotFoundException($this->translator->trans('Unable to find user: %id%', ['%id%' => $id])); + public function edit(Request $request, string $hash, string $mail): Response { + //With invalid hash + if ($hash != $this->slugger->hash($mail)) { + //Throw bad request + throw new BadRequestHttpException($this->translator->trans('Invalid %field% field: %value%', ['%field%' => 'hash', '%value%' => $hash])); } - //Get user token - $token = new UsernamePasswordToken($user, null, 'none', $user->getRoles()); + //Get mail + $mail = $this->slugger->unshort($smail = $mail); - //Check if guest - $isGuest = $this->get('rapsys_user.access_decision_manager')->decide($token, ['ROLE_GUEST']); + //With existing subscriber + if (empty($user = $this->doctrine->getRepository($this->config['class']['user'])->findOneByMail($mail))) { + //Throw not found + //XXX: prevent slugger reverse engineering by not displaying decoded mail + throw $this->createNotFoundException($this->translator->trans('Unable to find account %mail%', ['%mail%' => $smail])); + } //Prevent access when not admin, user is not guest and not currently logged user - if (!$this->isGranted('ROLE_ADMIN') && empty($isGuest) && $user != $this->getUser()) { - throw $this->createAccessDeniedException($this->translator->trans('Unable to access user: %id%', ['%id%' => $id])); + if (!$this->checker->isGranted('ROLE_ADMIN') && $user != $this->security->getUser() || !$this->checker->isGranted('IS_AUTHENTICATED_FULLY')) { + //Throw access denied + //XXX: prevent slugger reverse engineering by not displaying decoded mail + throw $this->createAccessDeniedException($this->translator->trans('Unable to access user: %mail%', ['%mail%' => $smail])); } - //Set section - $section = $user->getPseudonym(); - - //Set title - $title = $this->translator->trans($this->config['site']['title']).' - '.$section; - - //Set description - $this->context['description'] = $this->translator->trans('%pseudonym% outdoor Argentine Tango session calendar', [ '%pseudonym%' => $user->getPseudonym() ]); - - //Set keywords - $this->context['keywords'] = [ - $user->getPseudonym(), - $this->translator->trans('outdoor'), - $this->translator->trans('Argentine Tango'), - $this->translator->trans('calendar') - ]; - - //Compute period - $period = new \DatePeriod( - //Start from first monday of week - new \DateTime('Monday this week'), - //Iterate on each day - new \DateInterval('P1D'), - //End with next sunday and 4 weeks - new \DateTime( - $this->isGranted('IS_AUTHENTICATED_REMEMBERED')?'Monday this week + 3 week':'Monday this week + 2 week' - ) - ); - - //Fetch calendar - //TODO: highlight with current session route parameter - $calendar = $doctrine->getRepository(Session::class)->fetchUserCalendarByDatePeriod($this->translator, $period, $isGuest?$id:null, $request->get('session')); - - //Fetch locations - //XXX: we want to display all active locations anyway - $locations = $doctrine->getRepository(Location::class)->findTranslatedSortedByPeriod($this->translator, $period, $id); - - //Create user form for admin or current user - if ($this->isGranted('ROLE_ADMIN') || $user == $this->getUser()) { - //Create SnippetType form - $userForm = $this->createForm('Rapsys\AirBundle\Form\RegisterType', $user, [ - //Set action - 'action' => $this->generateUrl('rapsys_air_user_view', ['id' => $id]), - //Set the form attribute - 'attr' => [ 'class' => 'col' ], - //Set civility class - 'class_civility' => Civility::class, + //Create the RegisterType form and give the proper parameters + $edit = $this->factory->create($this->config['edit']['view']['edit'], $user, [ + //Set action to register route name and context + 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']), + //Set civility class + 'civility_class' => $this->config['class']['civility'], + //Set civility default + 'civility_default' => $this->doctrine->getRepository($this->config['class']['civility'])->findOneByTitle($this->config['default']['civility']), + //Set country class + 'country_class' => $this->config['class']['country'], + //Set country default + 'country_default' => $this->doctrine->getRepository($this->config['class']['country'])->findOneByTitle($this->config['default']['country']), + //Set country favorites + 'country_favorites' => $this->doctrine->getRepository($this->config['class']['country'])->findByTitle($this->config['default']['country_favorites']), + //Set dance + 'dance' => $this->checker->isGranted('ROLE_ADMIN'), + //Set dance choices + 'dance_choices' => $danceChoices = $this->doctrine->getRepository($this->config['class']['dance'])->findChoicesAsArray(), + //Set dance default + #'dance_default' => /*$this->doctrine->getRepository($this->config['class']['dance'])->findOneByNameType($this->config['default']['dance'])*/null, + //Set dance favorites + 'dance_favorites' => $this->doctrine->getRepository($this->config['class']['dance'])->findIdByNameTypeAsArray($this->config['default']['dance_favorites']), + //Set subscription + 'subscription' => $this->checker->isGranted('ROLE_ADMIN'), + //Set subscription choices + 'subscription_choices' => $subscriptionChoices = $this->doctrine->getRepository($this->config['class']['user'])->findChoicesAsArray(), + //Set subscription default + #'subscription_default' => /*$this->doctrine->getRepository($this->config['class']['user'])->findOneByPseudonym($this->config['default']['subscription'])*/null, + //Set subscription favorites + 'subscription_favorites' => $this->doctrine->getRepository($this->config['class']['user'])->findIdByPseudonymAsArray($this->config['default']['subscription_favorites']), + //Disable mail + 'mail' => $this->checker->isGranted('ROLE_ADMIN'), + //Disable pseudonym + 'pseudonym' => $this->checker->isGranted('ROLE_GUEST'), + //Disable password + 'password' => false, + //Set method + 'method' => 'POST' + ]+$this->config['edit']['field']); + + //With admin role + if ($this->checker->isGranted('ROLE_ADMIN')) { + //Create the ResetType form and give the proper parameters + $reset = $this->factory->create($this->config['edit']['view']['reset'], $user, [ + //Set action to register route name and context + 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']), //Disable mail - 'mail' => $this->isGranted('ROLE_ADMIN'), - //Disable password - 'password' => false + 'mail' => false, + //Set method + 'method' => 'POST' ]); - //Init user to context - $this->context['forms']['user'] = $userForm->createView(); - - //Check if submitted + //With post method if ($request->isMethod('POST')) { //Refill the fields in case the form is not valid. - $userForm->handleRequest($request); - - //Handle invalid form - if (!$userForm->isSubmitted() || !$userForm->isValid()) { - //Render the view - return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context); - } - - //Get data - $data = $userForm->getData(); - - //Get manager - $manager = $doctrine->getManager(); - - //Queue snippet save - $manager->persist($data); - - //Flush to get the ids - $manager->flush(); - - //Add notice - $this->addFlash('notice', $this->translator->trans('User %id% updated', ['%id%' => $id])); - - //Extract and process referer - if ($referer = $request->headers->get('referer')) { - //Create referer request instance - $req = Request::create($referer); - - //Get referer path - $path = $req->getPathInfo(); + $reset->handleRequest($request); - //Get referer query string - $query = $req->getQueryString(); + //With reset submitted and valid + if ($reset->isSubmitted() && $reset->isValid()) { + //Set data + $data = $reset->getData(); - //Remove script name - $path = str_replace($request->getScriptName(), '', $path); + //Set password + $data->setPassword($this->hasher->hashPassword($data, $data->getPassword())); - //Try with referer path - try { - //Save old context - $oldContext = $this->router->getContext(); + //Queue user password save + $this->manager->persist($data); - //Force clean context - //XXX: prevent MethodNotAllowedException because current context method is POST in onevendor/symfony/routing/Matcher/Dumper/CompiledUrlMatcherTrait.php+42 - $this->router->setContext(new RequestContext()); + //Flush to get the ids + $this->manager->flush(); - //Retrieve route matching path - $route = $this->router->match($path); + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% password updated', ['%mail%' => $mail])); - //Reset context - $this->router->setContext($oldContext); - - //Clear old context - unset($oldContext); - - //Extract name - $name = $route['_route']; - - //Remove route and controller from route defaults - unset($route['_route'], $route['_controller']); + //Redirect to cleanup the form + return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']); + } + } - //Check if user view route - if ($name == 'rapsys_air_user_view' && !empty($route['id'])) { - //Replace id - $route['id'] = $data->getId(); - //Other routes + //Add reset view + $this->config['edit']['view']['context']['reset'] = $reset->createView(); + + //Add google calendar array + $this->config['edit']['view']['context']['calendar'] = [ + //Form by mail + 'form' => [], + //Uri to link account + 'link' => null, + //Logo + 'logo' => [ + 'png' => '@RapsysAir/png/calendar.png', + 'svg' => '@RapsysAir/svg/calendar.svg' + ] + ]; + + //Get google client + $googleClient = new \Google\Client( + [ + 'application_name' => $request->server->get('GOOGLE_PROJECT'), + 'client_id' => $request->server->get('GOOGLE_CLIENT'), + 'client_secret' => $request->server->get('GOOGLE_SECRET'), + 'redirect_uri' => $this->generateUrl('rapsys_air_google_callback', [], UrlGeneratorInterface::ABSOLUTE_URL), + 'scopes' => self::googleScopes, + 'access_type' => 'offline', + 'login_hint' => $user->getMail(), + //XXX: see https://stackoverflow.com/questions/10827920/not-receiving-google-oauth-refresh-token + #'approval_prompt' => 'force' + 'prompt' => 'consent' + ] + ); + + //With user tokens + if (!($googleTokens = $user->getGoogleTokens())->isEmpty()) { + //Iterate on each google token + //XXX: either we finish with a valid token set or a logic exception after token removal + foreach($googleTokens as $googleToken) { + //Clear client cache before changing access token + //TODO: set a per token cache ? + $googleClient->getCache()->clear(); + + //Set access token + $googleClient->setAccessToken( + [ + 'access_token' => $googleToken->getAccess(), + 'refresh_token' => $googleToken->getRefresh(), + 'created' => $googleToken->getCreated()->getTimestamp(), + 'expires_in' => $googleToken->getExpired()->getTimestamp() - (new \DateTime('now'))->getTimestamp(), + ] + ); + + //With expired token + if ($googleClient->isAccessTokenExpired()) { + //Refresh token + if (($refresh = $googleClient->getRefreshToken()) && ($token = $googleClient->fetchAccessTokenWithRefreshToken($refresh)) && empty($token['error'])) { + //Set access token + $googleToken->setAccess($token['access_token']); + + //Set expires + $googleToken->setExpired(new \DateTime('+'.$token['expires_in'].' second')); + + //Set refresh + $googleToken->setRefresh($token['refresh_token']); + + //Queue google token save + $this->manager->persist($googleToken); + + //Flush to get the ids + $this->manager->flush(); + //Refresh failed } else { - //Set user - $route['user'] = $data->getId(); + //Add error in flash message + $this->addFlash( + 'error', + $this->translator->trans( + empty($token['error'])?'Unable to refresh token':'Unable to refresh token: %error%', + empty($token['error'])?[]:['%error%' => str_replace('_', ' ', $token['error'])] + ) + ); + + //Remove user token + $this->manager->remove($googleToken); + + //Flush to delete it + $this->manager->flush(); + + //Skip to next token + continue; + } + } + + //XXX: TODO: remove DEBUG + #$this->cache->delete('user.edit.calendar.'.$this->slugger->short($googleToken->getMail())); + + //Get calendars + $calendars = $this->cache->get( + //Set key to user.edit.$mail + ($calendarKey = 'user.edit.calendar.'.($googleShortMail = $this->slugger->short($googleMail = $googleToken->getMail()))), + //Fetch mail calendar list + function (ItemInterface $item) use ($googleClient): array { + //Expire after 1h + $item->expiresAfter(3600); + + //Get google calendar service + $service = new \Google\Service\Calendar($googleClient); + + //Init calendars + $calendars = []; + + //Init counter + $count = 0; + + //Retrieve calendar + try { + //Set page token + $pageToken = null; + + //Iterate until next page token is null + do { + //Get token calendar list + //XXX: require permission to read and write events + $calendarList = $service->calendarList->listCalendarList(['pageToken' => $pageToken, 'minAccessRole' => 'writer', 'showHidden' => true]); + + //Iterate on items + foreach($calendarList->getItems() as $calendarItem) { + //With primary calendar + if ($calendarItem->getPrimary()) { + //Add primary calendar + //XXX: use primary as key as described in google api documentation + $calendars = ['primary' => $this->translator->trans('Primary') /*$calendarItem->getSummary()*/] + $calendars; + //With secondary calendar + } else { + //Add secondary calendar + //XXX: Append counter to make sure summary is unique for later array_flip call + $calendars += [$calendarItem->getId() => $calendarItem->getSummary().' ('.++$count.')']; + } + } + } while ($pageToken = $calendarList->getNextPageToken()); + //Catch exception + } catch(\Google\Service\Exception $e) { + //Throw error + throw new \LogicException('Calendar list failed', 0, $e); + } + + //Cache calendars + return $calendars; } + ); + + //Set formData array + $formData = ['calendar' => []]; + + //With google calendars + if (!($googleCalendars = $googleToken->getGoogleCalendars())->isEmpty()) { + //Iterate on each google calendars + foreach($googleCalendars as $googleCalendar) { + //With existing google calendar + if (isset($calendars[$googleCalendar->getMail()])) { + //Add google calendar to form data + $formData['calendar'][] = $googleCalendar->getMail(); + } else { + //Remove google calendar from database + $this->manager->remove($googleCalendar); + + //Flush to persist ids + $this->manager->flush(); + } + } + } - //Generate url - return $this->redirectToRoute($name, $route); - //No route matched - } catch(MethodNotAllowedException|ResourceNotFoundException $e) { - //Unset referer to fallback to default route - unset($referer); + //XXX: TODO: remove DEBUG + #header('Content-Type: text/plain'); + + //TODO: add feature to filter synchronized data (OrganizerId/DanceId) + //TODO: add feature for alerts (-30min/-1h) ? + //[Direct link to calendar ?][Direct link to calendar settings ?][Alerts][Remove] + + //Create the CalendarType form and give the proper parameters + $form = $this->factory->createNamed('calendar_'.$googleShortMail, 'Rapsys\AirBundle\Form\CalendarType', $formData, [ + //Set action to register route name and context + 'action' => $this->generateUrl($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']), + //Set calendar choices + //XXX: unique calendar summary required by choice widget is guaranteed by appending ' (x)' to secondary calendars earlier + 'calendar_choices' => array_flip($calendars), + //Set method + 'method' => 'POST' + ]); + + //With post method + if ($request->isMethod('POST')) { + //Refill the fields in case the form is not valid. + $form->handleRequest($request); + + //With reset submitted and valid + if ($form->isSubmitted() && $form->isValid()) { + //Set data + $data = $form->getData(); + + //Refresh button + if (($clicked = $form->getClickedButton()->getName()) == 'refresh') { + //Remove calendar key + $this->cache->delete($calendarKey); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% calendars updated', ['%mail%' => $googleMail])); + //Add button + } elseif ($clicked == 'add') { + //Get google calendar service + $service = new \Google\Service\Calendar($googleClient); + + //Add calendar + try { + //Instantiate calendar + $calendar = new \Google\Service\Calendar\Calendar( + [ + 'summary' => $this->translator->trans($this->config['context']['site']['title']), + 'timeZone' => date_default_timezone_get() + ] + ); + + //Insert calendar + $service->calendars->insert($calendar); + //Catch exception + } catch(\Google\Service\Exception $e) { + //Throw error + throw new \LogicException('Calendar insert failed', 0, $e); + } + + //Remove calendar key + $this->cache->delete($calendarKey); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% calendar added', ['%mail%' => $googleMail])); + //Delete button + } elseif ($clicked == 'delete') { + //Get google calendar service + $service = new \Google\Service\Calendar($googleClient); + + //Remove calendar + try { + //Set site title + $siteTitle = $this->translator->trans($this->config['context']['site']['title']); + + //Iterate on calendars + foreach($calendars as $calendarId => $calendarSummary) { + //With calendar matching site title + if (substr($calendarSummary, 0, strlen($siteTitle)) == $siteTitle) { + //Delete the calendar + $service->calendars->delete($calendarId); + } + } + //Catch exception + } catch(\Google\Service\Exception $e) { + //Throw error + throw new \LogicException('Calendar delete failed', 0, $e); + } + + //Remove calendar key + $this->cache->delete($calendarKey); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% calendars deleted', ['%mail%' => $googleMail])); + //Unlink button + } elseif ($clicked == 'unlink') { + //Iterate on each google calendars + foreach($googleCalendars as $googleCalendar) { + //Remove google calendar from database + $this->manager->remove($googleCalendar); + } + + //Remove google token from database + $this->manager->remove($googleToken); + + //Flush to persist + $this->manager->flush(); + + //Revoke access token + $googleClient->revokeToken($googleToken->getAccess()); + + //With refresh token + if ($refresh = $googleToken->getRefresh()) { + //Revoke refresh token + $googleClient->revokeToken($googleToken->getRefresh()); + } + + //Remove calendar key + $this->cache->delete($calendarKey); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% calendars unlinked', ['%mail%' => $googleMail])); + //Submit button + } else { + //Flipped calendar data + $dataCalendarFlip = array_flip($data['calendar']); + + //Iterate on each google calendars + foreach($googleCalendars as $googleCalendar) { + //Without calendar in flipped data + if (!isset($dataCalendarFlip[$googleCalendarMail = $googleCalendar->getMail()])) { + //Remove google calendar from database + $this->manager->remove($googleCalendar); + //With calendar in flipped data + } else { + //Remove google calendar from calendar data + unset($data['calendar'][$dataCalendarFlip[$googleCalendarMail]]); + } + } + + //Iterate on remaining calendar data + foreach($data['calendar'] as $googleCalendarMail) { + //Create new google calendar + //XXX: remove trailing ' (x)' from summary + $googleCalendar = new GoogleCalendar($googleToken, $googleCalendarMail, preg_replace('/ \([0-9]\)$/', '', $calendars[$googleCalendarMail])); + + //Queue google calendar save + $this->manager->persist($googleCalendar); + } + + //Flush to persist ids + $this->manager->flush(); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% calendars updated', ['%mail%' => $googleMail])); + } + + //Redirect to cleanup the form + return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail, 'hash' => $hash]+$this->config['route']['edit']['context']); + } } - } - //Redirect to cleanup the form - return $this->redirectToRoute('rapsys_air', ['user' => $data->getId()]); + //Add form view + $this->config['edit']['view']['context']['calendar']['form'][$googleToken->getMail()] = $form->createView(); + } } + + //Add google calendar auth url + $this->config['edit']['view']['context']['calendar']['link'] = $googleClient->createAuthUrl(); } - //Create snippet forms for role_guest - if ($this->isGranted('ROLE_ADMIN') || ($this->isGranted('ROLE_GUEST') && $user == $this->getUser())) { - //Fetch all user snippet - $snippets = $doctrine->getRepository(Snippet::class)->findByLocaleUserId($request->getLocale(), $id); + //With post method + if ($request->isMethod('POST')) { + //Refill the fields in case the form is not valid. + $edit->handleRequest($request); + + //With edit submitted and valid + if ($edit->isSubmitted() && $edit->isValid()) { + //Set data + $data = $edit->getData(); + + //Queue user save + $this->manager->persist($data); + + //Try saving in database + try { + //Flush to get the ids + $this->manager->flush(); + + //Add notice + //XXX: get mail from data as it may change + $this->addFlash('notice', $this->translator->trans('Account %mail% updated', ['%mail%' => $mail = $data->getMail()])); + + //Redirect to cleanup the form + return $this->redirectToRoute($this->config['route']['edit']['name'], ['mail' => $smail = $this->slugger->short($mail), 'hash' => $this->slugger->hash($smail)]+$this->config['route']['edit']['context']); + //Catch double slug or mail + } catch (UniqueConstraintViolationException $e) { + //Add error message mail already exists + $this->addFlash('error', $this->translator->trans('Account %mail% already exists', ['%mail%' => $data->getMail()])); + } + } + //Without admin role + //XXX: prefer a reset on login to force user unspam action + } elseif (!$this->checker->isGranted('ROLE_ADMIN')) { + //Add notice + $this->addFlash('notice', $this->translator->trans('To change your password login with your mail and any password then follow the procedure')); + } - //Rekey by location id - $snippets = array_reduce($snippets, function($carry, $item){$carry[$item->getLocation()->getId()] = $item; return $carry;}, []); + //Render view + return $this->render( + //Template + $this->config['edit']['view']['name'], + //Context + ['edit' => $edit->createView(), 'sent' => $request->query->get('sent', 0)]+$this->config['edit']['view']['context'] + ); + } - //Init snippets to context - $this->context['forms']['snippets'] = []; + /** + * Handle google callback + * + * @param Request $request The request + * @return Response The response + */ + public function googleCallback(Request $request): Response { + //Without code + if (empty($code = $request->query->get('code', ''))) { + throw new \InvalidArgumentException('Query parameter code is empty'); + } - //Iterate on locations - foreach($locations as $locationId => $location) { - //Init snippet - $snippet = new Snippet(); + //Without user + if (empty($user = $this->getUser())) { + throw new \LogicException('User is empty'); + } - //Set default locale - $snippet->setLocale($request->getLocale()); + //Get google client + $googleClient = new \Google\Client( + [ + 'application_name' => $request->server->get('GOOGLE_PROJECT'), + 'client_id' => $request->server->get('GOOGLE_CLIENT'), + 'client_secret' => $request->server->get('GOOGLE_SECRET'), + 'redirect_uri' => $this->generateUrl('rapsys_air_google_callback', [], UrlGeneratorInterface::ABSOLUTE_URL), + 'scopes' => self::googleScopes, + 'access_type' => 'offline', + 'login_hint' => $user->getMail(), + #'approval_prompt' => 'force' + 'prompt' => 'consent' + ] + ); - //Set default user - $snippet->setUser($user); + //Protect to extract failure + try { + //Authenticate with code + if (!empty($token = $googleClient->authenticate($code))) { + //With error + if (!empty($token['error'])) { + throw new \LogicException('Client authenticate failed: '.str_replace('_', ' ', $token['error'])); + //Without refresh token + } elseif (empty($token['refresh_token'])) { + throw new \LogicException('Refresh token is empty'); + //Without expires in + } elseif (empty($token['expires_in'])) { + throw new \LogicException('Expires in is empty'); + //Without scope + } elseif (empty($token['scope'])) { + throw new \LogicException('Scope in is empty'); + //Without valid scope + } elseif (array_intersect(self::googleScopes, explode(' ', $token['scope'])) != self::googleScopes) { + throw new \LogicException('Scope in is not valid'); + } - //Set default location - $snippet->setLocation($doctrine->getRepository(Location::class)->findOneById($locationId)); + //Get Oauth2 object + $oauth2 = new \Google\Service\Oauth2($googleClient); + + //Protect user info get call + try { + //Retrieve user info + $userInfo = $oauth2->userinfo->get(); + //Catch exception + } catch(\Google\Service\Exception $e) { + //Throw error + throw new \LogicException('Userinfo get failed', 0, $e); + } - //Get snippet - if (!empty($snippets[$locationId])) { - $snippet = $snippets[$locationId]; + //With existing token + if ( + //If available retrieve google token with matching mail + $googleToken = array_reduce( + $user->getGoogleTokens()->getValues(), + function ($c, $i) use ($userInfo) { + if ($i->getMail() == $userInfo['email']) { + return $i; + } + }, + (object)[] + ) + ) { + //Set mail + //XXX: TODO: should already be set and not change, remove ? + //XXX: TODO: store picture as well ? + $googleToken->setMail($userInfo['email']); + + //Set access token + $googleToken->setAccess($token['access_token']); + + //Set expires + $googleToken->setExpired(new \DateTime('+'.$token['expires_in'].' second')); + + //Set refresh + $googleToken->setRefresh($token['refresh_token']); + } else { + //Create new token + //XXX: TODO: store picture as well ? + $googleToken = new GoogleToken($user, $userInfo['email'], $token['access_token'], new \DateTime('+'.$token['expires_in'].' second'), $token['refresh_token']); } - //Create SnippetType form - #$form = $this->createForm('Rapsys\AirBundle\Form\SnippetType', $snippet, [ - $form = $this->container->get('form.factory')->createNamed('snipped_'.$request->getLocale().'_'.$locationId, 'Rapsys\AirBundle\Form\SnippetType', $snippet, [ - //Set the action - //TODO: voir si on peut pas faire sauter ça ici - 'action' => - !empty($snippet->getId()) ? - $this->generateUrl('rapsys_air_snippet_edit', ['id' => $snippet->getId()]) : - $this->generateUrl('rapsys_air_snippet_add', ['location' => $locationId]), - #'action' => $this->generateUrl('rapsys_air_snippet_add'), - //Set the form attribute - 'attr' => [], - //Set csrf_token_id - //TODO: would maybe need a signature field - //'csrf_token_id' => $request->getLocale().'_'.$id.'_'.$locationId - ]); - #return $this->container->get('form.factory')->create($type, $data, $options); - #public function createNamed($name, $type = 'Symfony\Component\Form\Extension\Core\Type\FormType', $data = null, array $options = []); - - //Add form to context - $this->context['forms']['snippets'][$locationId] = $form->createView(); + //Queue google token save + $this->manager->persist($googleToken); + + //Flush to get the ids + $this->manager->flush(); + + //Add notice + $this->addFlash('notice', $this->translator->trans('Account %mail% google token updated', ['%mail%' => $user->getMail()])); + //With failed authenticate + } else { + throw new \LogicException('Client authenticate failed'); } + //Catch exception + } catch(\Exception $e) { + //Add notice + $this->addFlash('error', $this->translator->trans('Account %mail% google token rejected: %error%', ['%mail%' => $user->getMail(), '%error%' => $e->getMessage()])); } - //Render the view - return $this->render('@RapsysAir/user/view.html.twig', ['id' => $id, 'title' => $title, 'section' => $section, 'calendar' => $calendar, 'locations' => $locations]+$this->context); + //Redirect to user + return $this->redirectToRoute('rapsysuser_edit', ['mail' => $short = $this->slugger->short($user->getMail()), 'hash' => $this->slugger->hash($short)]); } }