Activate Google Authenticator

@param Request $request

@return Response
186219
public function activateGoogleAuthAction(Request $request)
    {
        $user = $this->getUser();
        
        $secret = $this->container->get("scheb_two_factor.security.google_authenticator")->generateSecret();
        $user->setGoogleAuthenticatorSecret($secret);

        //Generate QR url
        $qrUrl = $this->container->get("scheb_two_factor.security.google_authenticator")->getUrl($user);

        $form = $this->createForm(GoogleAuthType::class, $user);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->get('fos_user.user_manager')->updateUser($user, true);

            $this->addFlash('success', 'Your profile was updated successfully!');

            return $this->redirectToRoute('opifer_cms_user_profile');
        }

        return $this->render('OpiferCmsBundle:Backend/User:google_auth.html.twig', [
            'form' => $form->createView(),
            'secret' => $secret,
            'user' => $user,
            'qrUrl' => $qrUrl,
        ]);
    }
1279711
public function authorizeAction(Request $request)
    {
        $context = new Context(Context::CONTEXT_OAUTH2_NATIVE);
        $this->dispatch(PhraseaEvents::PRE_AUTHENTICATE, new PreAuthenticate($request, $context));

        //Check for auth params, send error or redirect if not valid
        $params = $this->oAuth2Adapter->getAuthorizationRequestParameters($request);

        $appAuthorized = false;
        $error = $request->get('error', '');

        /** @var ApiApplicationRepository $appRepository */
        $appRepository = $this->app['repo.api-applications'];
        if (null === $client = $appRepository->findByClientId($params['client_id'])) {
            throw new NotFoundHttpException(sprintf('Application with client id %s could not be found', $params['client_id']));
        }

        $this->oAuth2Adapter->setClient($client);

        $actionAccept = $request->get("action_accept");
        $actionLogin = $request->get("action_login");

        $template = "api/auth/end_user_authorization.html.twig";

        $custom_template = sprintf(
            "%s/config/templates/web/api/auth/end_user_authorization/%s.html.twig"
            , $this->app['root.path']
            , $client->getId()
        );

        if (file_exists($custom_template)) {
            $template = sprintf(
                'api/auth/end_user_authorization/%s.html.twig'
                , $client->getId()
            );
        }

        if (!$this->getAuthenticator()->isAuthenticated()) {
            if ($actionLogin !== null) {
                try {
                    /** @var PasswordAuthenticationInterface $authentication */
                    $authentication = $this->app['auth.native'];
                    if (null === $usrId = $authentication->getUsrId($request->get("login"), $request->get("password"), $request)) {
                        $this->getSession()->getFlashBag()
                            ->set('error', $this->app->trans('login::erreur: Erreur d\'authentification'));

                        return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'login'), $params));
                    }
                } catch (RequireCaptchaException $e) {
                    return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'captcha'), $params));
                } catch (AccountLockedException $e) {
                    return $this->app->redirectPath('oauth2_authorize', array_merge(array('error' => 'account-locked'), $params));
                }

                $user = $this->getUserRepository()->find($usrId);
                $this->getAuthenticator()->openAccount($user);
                $event = new PostAuthenticate($request, new Response(), $user, $context);
                $this->dispatch(PhraseaEvents::POST_AUTHENTICATE, $event);
            } else {
                $r = new Response($this->render($template, array('error' => $error, "auth" => $this->oAuth2Adapter)));
                $r->headers->set('Content-Type', 'text/html');

                return $r;
            }
        }

        $account = $this->oAuth2Adapter->updateAccount($this->getAuthenticatedUser());

        //check if current client is already authorized by current user
        $clients = $appRepository->findAuthorizedAppsByUser($this->getAuthenticatedUser());

        foreach ($clients as $authClient) {
            if ($client->getClientId() == $authClient->getClientId()) {
                $appAuthorized = true;
                break;
            }
        }

        $params['account_id'] = $account->getId();

        if (!$appAuthorized && $actionAccept === null) {
            $params = [
                "auth"  => $this->oAuth2Adapter,
                "error" => $error,
            ];

            $r = new Response($this->render($template, $params));
            $r->headers->set('Content-Type', 'text/html');

            return $r;
        } elseif (!$appAuthorized && $actionAccept !== null) {
            $appAuthorized = (Boolean) $actionAccept;
            if ($appAuthorized) {
                $this->getApiAccountManipulator()
                    ->authorizeAccess($account);
            } else {
                $this->getApiAccountManipulator()
                    ->revokeAccess($account);
            }
        }

        //if native app show template
        if ($this->oAuth2Adapter->isNativeApp($params['redirect_uri'])) {
            $params = $this->oAuth2Adapter->finishNativeClientAuthorization($appAuthorized, $params);

            $r = new Response($this->render("api/auth/native_app_access_token.html.twig", $params));
            $r->headers->set('Content-Type', 'text/html');

            return $r;
        }

        $this->oAuth2Adapter->finishClientAuthorization($appAuthorized, $params);

        // As OAuth2 library already outputs response content, we need to send an empty
        // response to avoid breaking silex controller
        return '';
    }
11108
public function registerConfirm(Request $request)
    {
        if (null === $code = $request->query->get('code')) {
            $this->app->addFlash('error', $this->app->trans('Invalid unlock link.'));

            return $this->app->redirectPath('homepage');
        }

        if (null === $token = $this->getTokenRepository()->findValidToken($code)) {
            $this->app->addFlash('error', $this->app->trans('Invalid unlock link.'));

            return $this->app->redirectPath('homepage');
        }

        $user = $token->getUser();

        if (!$user->isMailLocked()) {
            $this->app->addFlash('info', $this->app->trans('Account is already unlocked, you can login.'));

            return $this->app->redirectPath('homepage');
        }

        $tokenManipulator = $this->getTokenManipulator();
        $tokenManipulator->delete($token);
        $user->setMailLocked(false);

        try {
            $receiver = Receiver::fromUser($user);
        } catch (InvalidArgumentException $e) {
            $this->app->addFlash('success', $this->app->trans('Account has been unlocked, you can now login.'));

            return $this->app->redirectPath('homepage');
        }

        $tokenManipulator->delete($token);

        if (count($this->getAclForUser($user)->get_granted_base()) > 0) {
            $mail = MailSuccessEmailConfirmationRegistered::create($this->app, $receiver);
            $this->deliver($mail);

            $this->app->addFlash('success', $this->app->trans('Account has been unlocked, you can now login.'));
        } else {
            $mail = MailSuccessEmailConfirmationUnregistered::create($this->app, $receiver);
            $this->deliver($mail);

            $this->app->addFlash('info', $this->app->trans('Account has been unlocked, you still have to wait for admin approval.'));
        }

        return $this->app->redirectPath('homepage');
    }
163049
public function authenticate(Request $request)
    {
        if ($this->session->hasValue(User::SESSION_KEY)) {
            return $this->session->value(User::SESSION_KEY);
        }

        $user = $this->authenticationProvider->authenticate($request);
        if (null === $user) {
            return null;
        }

        $this->session->putValue(User::SESSION_KEY, $user);
        return $user;
    }
150976
public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        return response()->json(compact('token'));
    }
1211036
public function reset(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'token'    => 'required',
            'email'    => 'required|email',
            'password' => 'required|confirmed|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $credentials = $request->only('email', 'password', 'password_confirmation', 'token');

        $response = Password::reset($credentials, function ($user, $password) {

            $this->resetPassword($user, $password); // @codeCoverageIgnore
        });

        switch ($response) {
            case Password::PASSWORD_RESET:
                return response()->json(null, 200);

            default:
                return response()->json(null, 400);
        }
    }
317298
public function activate(Request $request)
    {
        if (!$email = $request->get('email')) {
            $email = null;
        }

        if (!$code = $request->get('code')) {
            $code = null;
        }

        if (!config('laraflock.dashboard.activations')) {
            Flash::error(trans('dashboard::dashboard.flash.activation.not_active'));

            return redirect()->route('auth.login');
        }

        return $this->view('auth.activate')->with(['email' => $email, 'code' => $code]);
    }
1173425
public function activationForm(Request $request): Response
    {
        $form = $this->createActivationForm();
        $form->handleRequest($request);

        if (!$form->isValid()) {
            return $this->render(
                $this->getConfigResolver()->getParameter('template.user.activate', 'ngsite'),
                [
                    'form' => $form->createView(),
                ]
            );
        }

        $users = $this->userService->loadUsersByEmail($form->get('email')->getData());

        $activationRequestEvent = new UserEvents\ActivationRequestEvent(
            $form->get('email')->getData(),
            $users[0] ?? null
        );

        $this->eventDispatcher->dispatch(SiteEvents::USER_ACTIVATION_REQUEST, $activationRequestEvent);

        return $this->render(
            $this->getConfigResolver()->getParameter('template.user.activate_sent', 'ngsite')
        );
    }
580699
public function register(Request $request)
    {

        $request->request->add(
            [
            'password_confirmation' => $request->has('passwordConfirmation') ? $request->passwordConfirmation : '']
        );
        $request->validate(
            [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
            ]
        );

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }
302394
public function authenticate(Request $request)
    {
        if ($request->hasSession()) {
            $request->session()->reflash();
        }

        return Broadcast::auth($request);
    }
496768
private function authCookie(Request $request) {
		if ($request->cookies->has(self::COOKIE_TOKEN_NAME)) {
			$token = $request->cookies->get(self::COOKIE_TOKEN_NAME);
			return $this->authToken($token);
		}
		return null;
	}
255158
public function postReauthenticate(Request $request)
    {
        $this->validate($request, [
            'password' => 'required',
        ]);

        $reauth = new ReauthLimiter($request);

        if (!$reauth->attempt($request->password)) {
            return Redirect::back()
                ->withErrors([
                    'password' => $this->getFailedLoginMessage(),
                ]);
        }

        return Redirect::intended();
    }
1069460
public function loginAction(Request $request)
    {
        if ($this->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED)) {
            return $this->redirectToRoute($this->getParameter('darvin_user.already_logged_in_redirect_route'));
        }

        return new Response($this->getSecurityFormRenderer()->renderLoginForm($request->isXmlHttpRequest()));
    }
1203047
public function authentication(Request $request, array $credentials)
    {
        if (!isset($credentials['username'], $credentials['password'])) {
            return $request;
        }
        if (!isset($credentials['realm'])) {
            $credentials = $this->_getServerInfo($request, $credentials);
        }
        if (!isset($credentials['realm'])) {
            return $request;
        }
        $value = $this->_generateHeader($request, $credentials);

        return $request->withHeader('Authorization', $value);
    }
1348619
public function activateAction(Request $request, $token)
    {
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->get('fos_user.resetting.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user = $userManager->findUserByConfirmationToken($token);

        if (!is_object($user) || !$user instanceof UserInterface) {
            return $this->redirectToRoute('fos_user_security_login');
        }

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();
        $form->setData($user);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $event = new FormEvent($form, $request);
            $dispatcher->dispatch(FOSUserEvents::RESETTING_RESET_SUCCESS, $event);

            $userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('fos_user_profile_show');
                $response = new RedirectResponse($url);
            }

            // remove the flash message listener
            $dispatcher->removeListener(
                FOSUserEvents::RESETTING_RESET_COMPLETED,
                [$this->get('fos_user.listener.flash'), 'addSuccessFlash']
            );

            $dispatcher->dispatch(
                FOSUserEvents::RESETTING_RESET_COMPLETED,
                new FilterUserResponseEvent($user, $request, $response)
            );

            $this->addFlash(
                'success',
                $this->get('translator')->trans('xm_security.activate.success', [], 'XMSecurityBundle')
            );

            return $response;
        }

        return $this->render('@XMSecurity/Activate/activate.html.twig', array(
            'token'       => $token,
            'form'        => $form->createView(),
            'target_path' => $this->getTargetPath($request),
        ));
    }
1231084
public function authenticate(Request $request)
    {
        if (config('eyewitness.login_disabled', false)) {
            return redirect('/');
        }

        if (! app(Eye::class)->checkConfig()) {
            return redirect()->route('eyewitness.login')->withError('Eyewitness has not been configured correctly. Login has been disabled for your security. Please run "php artisan eyewitness:debug" to determine the issue.');
        }

        if ($request->app_token !== config('eyewitness.app_token') ||
            $request->secret_key !== config('eyewitness.secret_key')) {
            return redirect()->route('eyewitness.login')->withError('Incorrect credentials.');
        }

        $request->session()->put('eyewitness:auth', 1);

        return redirect(route('eyewitness.dashboard').'#overview');
    }
1132904
public function authenticateAction(Request $request) {
        $data = $request->request->all();
        try {
            $data = $this->getAuthCredentials($request);
            $this->info('> Authenticate request', ['method' => $request->getMethod(), 'query' => $data]);
            // exports $client_id, $redirect_uri, $username and $password
            extract($data);

            $accessCredentials = $this->accessProvider->generate($request, $client_id, $redirect_uri, $username, $password);
            $response = new RedirectResponse($redirect_uri . '?code=' . $accessCredentials->getAuthCode());
        }catch (BadDataException $e) {
            $data['errors'] = $e->getErrors();
            $this->error('Bad Data Exception: ' . $e->getMessage(), ['errors' => $data['errors'], 'exception' => $e]);
            $response = $this->getBadFormRequestResponse($data);
        } catch (SoauthException $e) {
            $this->error('Soauth Exception: ' . $e->getMessage(), ['exception' => $e]);
            $response = $this->getBadFormRequestResponse($data);
        }

        $this->info('< Response', ['status_code' => $response->getStatusCode(), 'target' => $response instanceOf RedirectResponse ? $response->getTargetUrl() : null]);
        return $response;
    }