Create a rest session based on builders.

Give the request and resolver to builder to know if it is applicable
If yes, create and start the session from it

@param $request
@param $resolver
@return bool
@throws LoginFailedException
349289
public function createSessionFromRequest($request, $resolver)
    {
        if (!$this->isRestController($resolver)) {
            return false;
        }
        /** @var SessionBuilder $builder */
        foreach ($this->getSessionBuilders() as $builder) {
            if ($builder->isApplicable($request)) {
                return $this->startSession($builder->getSession($request));
            }
        }
        throw new LoginFailedException(array('Request cannot be authenticated.'));
    }
461208
public function callback(Request $request)
    {
        // Check to see if this provider exists and has a callback implemented
        $provider = strtolower($request->attributes->get('provider'));

        if (! $this->providerExists($provider)) {
            return $this->createNotFoundResponse();
        }

        if (! method_exists($this, $provider)) {
            throw new LogicException(sprintf(
                'Callback for provider \'%s\' not implemented',
                $provider
            ));
        }

        // Use provider service and access token from provider to create a LoginRequest for our app
        $code            = $request->query->get('code');
        $providerService = $this->getServiceByProvider($provider);
        $providerToken   = $providerService->requestAccessToken($code);

        $socialLoginRequest = $this->$provider($providerService, $providerToken);

        // Handle login or link-account request and redirect to the redirect-url
        $state = (int) $request->query->get('state');
        try {
            if ($state === self::ACTION_LOGIN_WITH_ACCOUNT) {
                $token = $this->service->handleLoginRequest($socialLoginRequest);
            } elseif ($state === self::ACTION_LINK_ACCOUNT) {
                $token = $this->service->handleLinkRequest(
                    $socialLoginRequest,
                    $this->session->get('user')
                );
            } else {
                return new Response(
                    'State parameter not set',
                    422
                );
            }

            $redirect = $this->config['redirect-url'];
            $redirect .= '?'.http_build_query($token);
        } catch (NoLinkedAccountException $e) {
            $redirect = $this->config['redirect-url'];
            $redirect .= '?login_failure=1&error=no_linked_account';
        } catch (LinkedAccountExistsException $e) {
            $redirect = $this->config['redirect-url'];
            $redirect .= '?login_failure=1&error=account_already_linked';
        } catch (OutOfBoundsException $e) {
            $redirect = $this->config['redirect-url'];
            $redirect .= '?login_failure=1';

            if ($e->getCode() === SocialLoginService::EXCEPTION_ACCOUNT_NOT_FOUND) {
                $redirect .= '&error=account_not_found';
            }
        }

        $response = new Response();
        $response->setStatusCode(301);
        $response->headers->set('Location', $redirect);

        return $response;
    }
71462
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
        {
            $cookies  = $request->getCookieParams();
            $name     = $this->name ?: session_name();
            $id       = $cookies[$name] ?? bin2hex(random_bytes(16));
            $options  = $this->options;
            $session  = $this->session->start($id, $name, $options);
            
            $request  = $request->withAttribute($this->sessionRequestAttribute, $session);
            $response = $handler->handle($request);
            $session->save();
            
            return isset($cookies[$name]) ? $response : $response->withHeader(
                'Set-Cookie',
                sprintf(
                    "%s=%s; path=%s", 
                    $name, 
                    $id, 
                    ini_get('session.cookie_path')
                )
            );
        }
1142361
private function login(Request $request)
    {
        $user = $this->loginProvider->authenticate($request);
        if (null !== $user) {
            try {
                $token = $user->createToken($this->tokenSalt);
                $this->tokenStore->store($request, $token, $user);
                return $user;
            } catch (\Exception $e) {
                throw new InternalAuthProviderException(
                        'Error while trying to store new token for user: ' . $e->getMessage(),
                        $e
                );
            }
        }

        return null;
    }
865716
public function logout(Request $request)
    {
        $content = json_decode($request->getContent(), true);

        $securityToken = $this->security->getToken();
        $user          = $securityToken->getUser();
        $accessToken   = $securityToken->getOAuthToken();
        $refreshToken  = Arr::get($content, 'refresh_token');

        $this->session->set('user', null);

        if (! $refreshToken) {
            return new Response('Refresh token not provided', 422);
        }

        try {
            $this->expireAccessToken($accessToken);
            $this->expireRefreshToken($refreshToken, $user);
        } catch (OutOfBoundsException $e) {
            return new Response($e->getMessage(), 422);
        }

        return new Response('', 200);
    }
1329827
public function handleLogin($request)
    {
        /** @var RedirectResponse $response */
        $response = $this->provider->redirect();
        $traitsUsed = class_uses($this->provider);
        $traitTwo = DfOAuthTwoProvider::class;
        $traitOne = DfOAuthOneProvider::class;
        if (isset($traitsUsed[$traitTwo])) {
            $state = $this->provider->getState();
            if (!empty($state)) {
                $key = static::CACHE_KEY_PREFIX . $state;
                \Cache::put($key, $this->getName(), 3);
            }
        } elseif (isset($traitsUsed[$traitOne])) {
            $token = $this->provider->getOAuthToken();
            if (!empty($token)) {
                $key = static::CACHE_KEY_PREFIX . $token;
                \Cache::put($key, $this->getName(), 3);
            }
        }

        if (!$request->ajax()) {
            return $response;
        }
        $url = $response->getTargetUrl();
        $result = ['response' => ['redirect' => true, 'url' => $url]];

        return $result;
    }
178305
protected function doRequest($request)
    {
        if (!$this->firstRequest) {
            $this->initialize($request);
        }
        $this->firstRequest = false;

        $this->applyBindings();
        $this->applyContextualBindings();
        $this->applyInstances();
        $this->applyApplicationHandlers();

        $request = Request::createFromBase($request);
        $response = $this->kernel->handle($request);
        $this->app->make('Illuminate\Contracts\Http\Kernel')->terminate($request, $response);

        return $response;
    }
573364
private function configureStartControlProperties(OptionsResolver $resolver)
    {
        $resolver->setDefined('autostart');
        $this->configureBooleanProperty('autostart', $resolver);


        $resolver
            ->setDefined('autorestart')
            ->setAllowedTypes('autorestart', ['bool', 'string'])
            ->setAllowedValues('autorestart', [true, false, 'true', 'false', 'unexpected'])
            ->setNormalizer('autorestart', function (Options $options, $value) {
                return (is_bool($value) or $value === 'unexpected') ? $value : ($value === 'true' ? true : false);
            });

        $resolver->setDefined('startsecs');
        $this->configureIntegerProperty('startsecs', $resolver);

        $resolver->setDefined('startretries');
        $this->configureIntegerProperty('startretries', $resolver);
    }
986719
public function run(Request $request) {
		$page = $this->getServiceContainer()->getKernel()->getApplication()->getPage();
		$page->setTitle($this->getServiceContainer()->getTranslator()->trans('sessions'));

		if ($request->isMethod('POST')) {
			$post = $request->request;
			if ($post->has('token')) {
				SessionQuery::create()->findOneByToken($post->get('token'))->delete();
				$service = $this->getServiceContainer();
				$accountUrl = $service->getPreferenceLoader()->getSystemPreferences()->getAccountUrl();
				$translator = $service->getTranslator();
				$url = sprintf('%s%s/%s',
					$accountUrl,
					$translator->trans('slug.settings'),
					$translator->trans('slug.settings.sessions')
				);
				return new RedirectResponse($url);
			}
		}

		return $this->responder->run($request);
	}
1171862
public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
1072148
protected function attachSession(Request $request)
    {
        // TODO consider generating this code based on the ContainerBuilder / PhpDumper from Symfony DI.
        $container = $this->bootLightweightContainer();

        if ($this->sessionConfig && @is_readable($this->getRootDir() . '/' . $this->sessionConfig)) {
            require_once $this->getRootDir() . '/' . $this->sessionConfig;

            if ($request->cookies->has($container->getParameter('session.name'))) {
                if (is_readable($this->getCacheDir() . '/classes.php')) {
                    require_once $this->getCacheDir() . '/classes.php';
                }
                $class = $container->getParameter('session.handler.class');

                $session = new Session\Session(
                    new Session\Storage\NativeSessionStorage(
                        array(
                            'cookie_path'   => $container->getParameter('session.cookie_path'),
                            'cookie_domain' => $container->getParameter('session.cookie_domain'),
                            'name'          => $container->getParameter('session.name')
                        ),
                        new $class($container->getParameter('session.handler.save_path')),
                        new Session\Storage\MetadataBag()
                    ),
                    new Session\Attribute\AttributeBag(),
                    new Session\Flash\FlashBag()
                );
                $this->lightweightContainer->set('session', $session);
                $request->setSession($session);
            }
        }
    }
161700
protected function sendFailedLoginResponse(Request $request)
    {
        $credentials = $this->credentials($request);

        $user = User::where('email', $credentials['email'])->first();
        if (!$user) {
            $error = __('This user was not found.');
        } elseif (!$user->activated) {
            $error = __('This user is not activated.');
        } else {
            $error = __('The password is incorrect.');
        }

        $errors = [$this->username() => $error];

        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }
1308451
public function createSessionAction(Request $request)
    {
        /** @var $sessionInput \eZ\Publish\Core\REST\Server\Values\SessionInput */
        $sessionInput = $this->inputDispatcher->parse(
            new Message(
                array('Content-Type' => $request->headers->get('Content-Type')),
                $request->getContent()
            )
        );
        $request->attributes->set('username', $sessionInput->login);
        $request->attributes->set('password', $sessionInput->password);

        try {
            $session = $request->getSession();
            if ($session->isStarted() && $this->hasStoredCsrfToken()) {
                $this->checkCsrfToken($request);
            }

            $token = $this->authenticator->authenticate($request);
            $csrfToken = $this->getCsrfToken();

            return new Values\UserSession(
                $token->getUser()->getAPIUser(),
                $session->getName(),
                $session->getId(),
                $csrfToken,
                !$token->hasAttribute('isFromSession')
            );
        } catch (Exceptions\UserConflictException $e) {
            // Already logged in with another user, this will be converted to HTTP status 409
            return new Values\Conflict();
        } catch (AuthenticationException $e) {
            $this->authenticator->logout($request);
            throw new UnauthorizedException('Invalid login or password', $request->getPathInfo());
        } catch (AccessDeniedException $e) {
            $this->authenticator->logout($request);
            throw new UnauthorizedException($e->getMessage(), $request->getPathInfo());
        }
    }
408440
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            /** @var User $user */
            $user = $token->getUser();
            $roles = $token->getRoles();
            $outputRoles = array();

            foreach ($roles as $role) {
                $outputRoles[] = $this->translator->trans('roles.' . $role->getRole(), array(), 'CodeLoversAngularBundle');
            }

            $output = $this->generator->getUserData($request, $token);

            // notify listeners to allow output modification
            $event = new LoginEvent($user);
            $event->setOutput($output);

            $this->dispatcher->dispatch(AuthEvents::LOGIN_SUCCESS, $event);

            return new JsonResponse($event->getOutput());
        } else {
            if ($targetPath = $request->getSession()->get('_security.target_path')) {
                $url = $targetPath;
            } else {
                $url = $this->getDefaultUrl();
            }

            return new RedirectResponse($url);
        }
    }
879104
public function requestApiKeyAction(Request $request)
    {
        /** @var \Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher */
        $dispatcher = $this->get('event_dispatcher');

        $credentials = [];
        if ($request->request->has('login')) {
            $credentials[$this->getPropertyName(ClassMetadata::LOGIN_PROPERTY)] = $request->request->get('login');
        }
        if ($request->request->has('password')) {
            $credentials[$this->getPropertyName(ClassMetadata::PASSWORD_PROPERTY)] = $request->request->get('password');
        }
        [$user, $exception] = $this->processAuthentication($credentials);

        /** @var OnAssembleResponseEvent $result */
        $result = $dispatcher->dispatch(
            Ma27ApiKeyAuthenticationEvents::ASSEMBLE_RESPONSE,
            new OnAssembleResponseEvent($user, $exception)
        );

        if (!$response = $result->getResponse()) {
            throw new HttpException(
                Response::HTTP_INTERNAL_SERVER_ERROR,
                'Cannot assemble the response!',
                $exception
            );
        }

        return $response;
    }
30309
public function start(HTTPRequest $request)
    {
        if ($this->isStarted()) {
            throw new BadMethodCallException("Session has already started");
        }

        $path = $this->config()->get('cookie_path');
        if (!$path) {
            $path = Director::baseURL();
        }
        $domain = $this->config()->get('cookie_domain');
        $secure = Director::is_https($request) && $this->config()->get('cookie_secure');
        $session_path = $this->config()->get('session_store_path');
        $timeout = $this->config()->get('timeout');

        // Director::baseURL can return absolute domain names - this extracts the relevant parts
        // for the session otherwise we can get broken session cookies
        if (Director::is_absolute_url($path)) {
            $urlParts = parse_url($path);
            $path = $urlParts['path'];
            if (!$domain) {
                $domain = $urlParts['host'];
            }
        }

        // If the session cookie is already set, then the session can be read even if headers_sent() = true
        // This helps with edge-case such as debugging.
        $data = [];
        if (!session_id() && (!headers_sent() || $this->requestContainsSessionId($request))) {
            if (!headers_sent()) {
                session_set_cookie_params($timeout ?: 0, $path, $domain ?: null, $secure, true);

                $limiter = $this->config()->get('sessionCacheLimiter');
                if (isset($limiter)) {
                    session_cache_limiter($limiter);
                }

                // Allow storing the session in a non standard location
                if ($session_path) {
                    session_save_path($session_path);
                }

                // If we want a secure cookie for HTTPS, use a separate session name. This lets us have a
                // separate (less secure) session for non-HTTPS requests
                // if headers_sent() is true then it's best to throw the resulting error rather than risk
                // a security hole.
                if ($secure) {
                    session_name($this->config()->get('cookie_name_secure'));
                }

                session_start();

                // Session start emits a cookie, but only if there's no existing session. If there is a session timeout
                // tied to this request, make sure the session is held for the entire timeout by refreshing the cookie age.
                if ($timeout && $this->requestContainsSessionId($request)) {
                    Cookie::set(session_name(), session_id(), $timeout / 86400, $path, $domain ?: null, $secure, true);
                }
            } else {
                // If headers are sent then we can't have a session_cache_limiter otherwise we'll get a warning
                session_cache_limiter(null);
            }

            if (isset($_SESSION)) {
                // Initialise data from session store if present
                $data = $_SESSION;

                // Merge in existing in-memory data, taking priority over session store data
                $this->recursivelyApply((array)$this->data, $data);
            }
        }

        // Save any modified session data back to the session store if present, otherwise initialise it to an array.
        $this->data = $data;

        $this->started = true;
    }
858717
public function configure(ResolverInterface $resolver): void
    {
        $resolver->type(Type::CALLABLE)
            ->validator(function (array $method) {
                return $this->validate($method);
            }, Type::ARRAY);
    }