Handler for AuthenticationSuccess. Returns a JsonResponse if request is an AJAX-request.
Returns a RedirectResponse otherwise.

@param Request $request
@param TokenInterface $token

@return Response
763838
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        // get url to redirect (or return in the JSON-response)
        if ($this->session->get('_security.admin.target_path')
            && false !== strpos($this->session->get('_security.admin.target_path'), '#')
        ) {
            $url = $this->session->get('_security.admin.target_path');
        } else {
            $url = $this->router->generate('sulu_admin');
        }

        if ($request->isXmlHttpRequest()) {
            // if AJAX login
            $array = ['url' => $url];
            $response = new JsonResponse($array, 200);
        } else {
            // if form login
            $response = new RedirectResponse($url);
        }

        return $response;
    }
1336217
public function logout(Request $request, Response $response, TokenInterface $token)
    {
        foreach ($this->cookies as $cookieName => $cookieData) {
            $response->headers->clearCookie($cookieName, $cookieData['path'], $cookieData['domain']);
        }
    }
197781
private function attemptExitUser(Request $request)
    {
        if (null === ($currentToken = $this->tokenStorage->getToken()) || null === $original = $this->getOriginalToken($currentToken)) {
            throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
        }

        if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
            $user = $this->provider->refreshUser($original->getUser());
            $switchEvent = new SwitchUserEvent($request, $user, $original);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            $original = $switchEvent->getToken();
        }

        return $original;
    }
1210080
public function handle(Request $request, Closure $next)
    {
        $tokenHeader = 'Token token="' . config('forum.api.token') . '"';
        if (auth()->check() || $request->header('Authorization') == $tokenHeader) {
            // User is authenticated or a valid API token was provided; continue the request
            return $next($request);
        } else {
            // No authentication/authorization

            if ($request->ajax()) {
                // For AJAX requests, just return the appropriate response
                return response()->json(['error' => "User must be authenticated to access this resource."], 401);
            }

            // For all other request types, attempt HTTP basic authentication
            return auth()->onceBasic() ?: $next($request);
        }
    }
1064632
public static function authorize(
        array $routeParams,
        ContainerInterface $container,
        ServerRequestInterface $request
    ): ResponseInterface {
        assert($routeParams !== null && $request !== null);

        /** @var PassportServerInterface $passportServer */
        $passportServer = $container->get(PassportServerInterface::class);
        $tokenResponse  = $passportServer->getCreateAuthorization($request);

        return $tokenResponse;
    }
23052
protected function getToken(ServerRequestInterface $request)
    {
        $token = $this->getTokenFromHeader($request, $this->getConfig('header'));
        if ($token === null) {
            $token = $this->getTokenFromQuery($request, $this->getConfig('queryParam'));
        }

        $prefix = $this->getConfig('tokenPrefix');
        if ($prefix !== null && is_string($token)) {
            return $this->stripTokenPrefix($token, $prefix);
        }

        return $token;
    }
886758
public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
	{
		// if AJAX login
		if ( ! $request->isXmlHttpRequest() ) {
			throw new NotFoundHttpException('Must use AJAX Login');
		}

		return new JsonResponse(array(
				"success" => false
		));
	}
356443
protected function getToken(Request $request)
    {
        try {
            $this->validateAuthorizationHeader($request);

            $token = $this->parseAuthorizationHeader($request);
        } catch (Exception $exception) {
            if (! $token = $request->query('token', false)) {
                throw $exception;
            }
        }

        return $token;
    }
38595
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        $user = $token->getUser();

        $this->dispatcher->dispatch(self::OAUTH_LOGIN_SUCCESS, new UserEvent($user));

        return $this->authResponseService->authenticateResponse($user,
            new Response($this->twig->render('@StarterKitStart/oauth-success.html.twig')));
    }
867058
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($user = $token->getUser()) {
            if (!$user->getFirstName() || !$user->getLastName()) {
                return new RedirectResponse($this->router->generate('opifer_cms_user_profile'));
            }
        }

        return parent::onAuthenticationSuccess($request, $token);
    }
992895
protected function authRedirect(RequestInterface $request)
    {
        unset($request);
        // Test if authentication is required.
        if ($this->authRequired() === false) {
            return;
        }

        // Test if user is authorized to access this controller
        if ($this->isAuthorized() === true) {
            return;
        }

        header('HTTP/1.0 403 Forbidden');
        exit;
    }
1369100
public function resetAction(Request $request, $token)
    {
        if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
            return new RedirectResponse($this->get('router')->generate('sonata_admin_dashboard'));
        }

        /** @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 $loginManager \FOS\UserBundle\Security\LoginManagerInterface */
        $loginManager = $this->get('fos_user.security.login_manager');

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

        $firewallName = $this->container->getParameter('fos_user.firewall_name');

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with "confirmation token" does not exist for value "%s"', $token));
        }

        if (!$user->isPasswordRequestNonExpired($this->container->getParameter('fos_user.resetting.token_ttl'))) {
            return new RedirectResponse($this->generateUrl('sonata_user_admin_resetting_request'));
        }

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

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user->setConfirmationToken(null);
            $user->setPasswordRequestedAt(null);
            $user->setEnabled(true);

            $message = $this->get('translator')->trans('resetting.flash.success', [], 'FOSUserBundle');
            $this->addFlash('success', $message);
            $response = new RedirectResponse($this->generateUrl('sonata_admin_dashboard'));

            try {
                $loginManager->logInUser($firewallName, $user, $response);
                $user->setLastLogin(new \DateTime());
            } catch (AccountStatusException $ex) {
                // We simply do not authenticate users which do not pass the user
                // checker (not enabled, expired, etc.).
                if ($this->has('logger')) {
                    $this->get('logger')->warning(sprintf(
                        'Unable to login user %d after password reset',
                        $user->getId())
                    );
                }
            }

            $userManager->updateUser($user);

            return $response;
        }

        return $this->render('NetworkingInitCmsBundle:Admin:Security/Resetting/reset.html.twig', [
            'token' => $token,
            'form' => $form->createView(),
            'base_template' => $this->get('sonata.admin.pool')->getTemplate('layout'),
            'admin_pool' => $this->get('sonata.admin.pool'),
        ]);
    }
1088768
public function resetAction(Request $request, PasswordResetToken $token): Response
    {
        $user = $this->userRepositoryCollection->findUserByToken($token);

        if ($user === null) {
            return new RedirectResponse(
                $this->router->generate('multi_user_login')
            );
        }

        $changePasswordTransferObject = ChangePasswordDataTransferObject::forUser($user);
        $form = $this->formFactory->create(ChangePasswordType::class, $changePasswordTransferObject);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->resetPasswordHandler->handle($form->getData());

            $this->flashBag->add(
                'success',
                $this->translator->trans(
                    'sumocoders.multiuserbundle.flash.password_reset_success'
                )
            );

            return new RedirectResponse(
                $this->router->generate('multi_user_login')
            );
        }

        return $this->templating->renderResponse(
            'SumoCodersFrameworkMultiUserBundle:PasswordReset:reset.html.twig',
            [
                'form' => $form->createView(),
            ]
        );
    }
1201949
public function filter($request)
    {
        // Check if user is authenticated via an auth session
        $this->session_authenticated = $this->isUserSessionAuthenticated();

        // Check if user is authenticated via an auth token
        $this->token_authenticated = $this->isUserTokenAuthenticated($request);

        // Decide if user is authenticated
        $this->user_authenticated = $this->isUserAuthenticated([$this->session_authenticated, $this->token_authenticated]);

        if ($this->user_authenticated === false)
        {
            // There is no way to know, for definite, which 'method' a user intended to authenticate, unless a token was
            // used, in which case it is safe to assume which method they were using.
            // In cases where a token wasn't given and the user has requested a JSON response, we assume they were trying
            // to use token authentication. Otherwise we assume they were trying to use session authentication.

            // Note: This approach maybe revised in the future.

            if (($this->token_authenticated !== false && $this->token_authenticated instanceof MissingTokenException === false) || Request::wantsJson())
            {
                $this->tokenAuthenticationFailure();
            }

            $this->sessionAuthenticationFailure();
            // BUG: For some reason issuing a redirect within a function other than this one doesn't do anything.
            return Redirect::guest('login');
        }
    }
531991
public function request($method, $url, $token, array $options = [])
    {
        $request = $this->getAuthenticatedRequest(
            $method, $url, $token, $options
        );

        return $this->getResponse($request);
    }
774439
public function process(Request $request, callable $next)
    {
        foreach ($this->preventOn() as $url) {
            if ($request->is($url)) {
                return $next($request);
            }
        }

        if ($request->isAjax()) {
            if ($request->getHeader('x-csrf-token') === session('_token')) {
                return $next($request);
            }

            response()->status(401);

            return response()->send('unauthorize.');
        }

        if ($request->get('_token') == $request->session()->get('_token')) {
            return $next($request);
        }

        throw new TokenMismatch('Token Mismatch');
    }
892873
public function authenticate(TokenInterface $token = null)
    {
        // If no token is passed in, try and find one from the authenticator
        $token = $token ?: $this->authenticator->present();

        if ( ! $token instanceof TokenInterface) {
            return new Result(Result::FAILURE_NO_TOKEN);
        }

        $result = new Result();

        try {
            $token = $this->authenticator->authenticate($token);
        } catch (AuthenticationException $e) {
            $result->setCode($e->getCode());
            $result->setException($e);
            $result->setToken($e->getToken());

            return $result;
        }

        $result->setCode(Result::SUCCESS);
        $result->setToken($token);

        if ( ! $token instanceof StatelessTokenInterface) {
            $this->storage->write($token);
        }

        $this->setToken($token);

        return $result;
    }