Attempt to authenticate using basic authentication.

@param  \Symfony\Component\HttpFoundation\Request  $request
@param  string  $field
@param  array  $extraConditions
@return bool
184451
protected function attemptBasic(Request $request, $field, $extraConditions = [])
    {
        if (! $request->getUser()) {
            return false;
        }

        return $this->attempt(array_merge(
            $this->basicCredentials($request, $field), $extraConditions
        ));
    }
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;
    }
1164381
public function authenticate($request) {
		if(!$this->configured)
			return;
		
		$this->checkValidity();
		
		if($this->via == self::HTTP_HEADER)
			$request->addHeader($this->description->http_header, $this->token);
	}
1082912
public function supports(Request $request)
    {
        $post = json_decode($request->getContent(), true);

        return !empty($post[self::TOKEN_FIELD]);
    }
1335155
protected function attemptBasic(Request $request, $field)
	{
		if ( ! $request->getUser()) return false;

		return $this->attempt($this->getBasicCredentials($request, $field));
	}
661097
protected function insertCredentials($request) {
		$request->setData('Username', $this->api_username);
		$request->setData('Password', $this->api_password);

		$signature = $this->signMerchantRequest($request);
		if($signature === FALSE) {
			return FALSE;
		}
		$request->setParam('Signature', $signature);

		return TRUE;
	}
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 '';
    }
1026452
protected function hasBasicAuth($request) : bool
  {
    if ($request->headers->has('Authorization') && starts_with($request->header('Authorization'), 'Basic ')) {
      return true;
    }

    return false;
  }
646789
public function validateRequestHandshake(
        $request
    ) {
        if (!$request) {
            return false;
        }

        list($request, $headers) = $this->getRequestHeaders($request);
        // make a copy of the headers array to store all extra headers
        $extraHeaders = $headers;

        // parse the resulting url to separate query parameters from the path
        $url = parse_url($this->validateRequestLine($request));
        $path = isset($url['path']) ? $url['path'] : null;
        $urlParams = [];
        if (isset($url['query'])) {
            parse_str($url['query'], $urlParams);
        }

        if (empty($headers[self::HEADER_ORIGIN])) {
            throw new BadRequestException('No origin header');
        } else {
            unset($extraHeaders[self::HEADER_ORIGIN]);
        }

        $origin = $headers[self::HEADER_ORIGIN];

        if (!isset($headers[self::HEADER_UPGRADE])
            || strtolower($headers[self::HEADER_UPGRADE]) != self::UPGRADE_VALUE
        ) {
            throw new BadRequestException('Invalid upgrade header');
        } else {
            unset($extraHeaders[self::HEADER_UPGRADE]);
        }

        if (!isset($headers[self::HEADER_CONNECTION])
            || stripos($headers[self::HEADER_CONNECTION], self::CONNECTION_VALUE) === false
        ) {
            throw new BadRequestException('Invalid connection header');
        } else {
            unset($extraHeaders[self::HEADER_CONNECTION]);
        }

        if (!isset($headers[self::HEADER_HOST])) {
            // @todo Validate host == listening socket? Or would that break
            //        TCP proxies?
            throw new BadRequestException('No host header');
        } else {
            unset($extraHeaders[self::HEADER_HOST]);
        }

        if (!isset($headers[self::HEADER_VERSION])) {
            throw new BadRequestException('No version header received on handshake request');
        }

        if (!$this->acceptsVersion($headers[self::HEADER_VERSION])) {
            throw new BadRequestException('Unsupported version: ' . $headers[self::HEADER_VERSION]);
        } else {
            unset($extraHeaders[self::HEADER_VERSION]);
        }

        if (!isset($headers[self::HEADER_KEY])) {
            throw new BadRequestException('No key header received');
        }

        $key = trim($headers[self::HEADER_KEY]);

        if (!$key) {
            throw new BadRequestException('Invalid key');
        } else {
            unset($extraHeaders[self::HEADER_KEY]);
        }

        // Optional
        $protocol = null;
        if (isset($headers[self::HEADER_PROTOCOL])) {
            $protocol = $headers[self::HEADER_PROTOCOL];
            unset($extraHeaders[self::HEADER_PROTOCOL]);
        }

        $extensions = [];
        if (!empty($headers[self::HEADER_EXTENSIONS])) {
            $extensions = $headers[self::HEADER_EXTENSIONS];
            if (is_scalar($extensions)) {
                $extensions = [$extensions];
            }
        }
        unset($extraHeaders[self::HEADER_EXTENSIONS]);

        return [$path, $origin, $key, $extensions, $protocol, $extraHeaders, $urlParams];
    }
1010721
function process_request (&$request)
    {
        if(isset($request->user) && !$request->user->isAnonymous()){
            return false;
        }
        if (! isset($request->SERVER['PHP_AUTH_USER'])) {
            return false;
        }
        
        $auth = array(
                'login' => $request->SERVER['PHP_AUTH_USER'],
                'password' => $request->SERVER['PHP_AUTH_PW']
        );
        foreach (Pluf::f('auth_backends', 
                array(
                        'User_Auth_ModelBackend'
                )) as $backend) {
            $user = call_user_func(
                    array(
                            $backend,
                            'authenticate'
                    ), $auth);
            if ($user !== false) {
                break;
            }
        }
        if($user){
            $request->user = $user;
        }
        return false;
    }
1016338
public function authenticate(Request $request)
    {
        $token = $this->readToken($request);
        if (null === $token || $token->isEmpty()) {
            return $this->login($request);
        }

        try {
            $user = $this->tokenStore->findUserByToken($request, $token);
            return null === $user ? $this->login($request) : $user->setToken($token);
        } catch (\Exception $e) {
            throw new InternalAuthProviderException(
                    'Error while trying to find user by token: ' . $e->getMessage(),
                    $e
            );
        }
    }
13002
public function beforeSave(Field $field, $post)
    {
        // FIX Removes the "dummy" input from extra if exists, the "dummy" input is
        // used to force Field Handler to work when empty POST information is sent
        $extra = [];
        foreach ((array)$field->extra as $k => $v) {
            if (is_integer($k)) {
                $extra[] = $v;
            }
        }
        $field->set('extra', $extra);

        $files = (array)$post;
        if (!empty($files)) {
            $value = [];
            foreach ($files as $k => $file) {
                if (!is_integer($k)) {
                    unset($files[$k]);
                    continue;
                } else {
                    $file = array_merge([
                        'mime_icon' => '',
                        'file_name' => '',
                        'file_size' => '',
                        'description' => '',
                    ], (array)$file);
                }
                $value[] = trim("{$file['file_name']} {$file['description']}");
            }
            $field->set('value', implode(' ', $value));
            $field->set('extra', $files);
        }

        if ($field->metadata->value_id) {
            $newFileNames = Hash::extract($files, '{n}.file_name');

            try {
                $prevFiles = (array)TableRegistry::get('Eav.EavValues')
                    ->get($field->metadata->value_id)
                    ->extra;
            } catch (\Exception $ex) {
                $prevFiles = [];
            }

            foreach ($prevFiles as $f) {
                if (!in_array($f['file_name'], $newFileNames)) {
                    $file = normalizePath(WWW_ROOT . "/files/{$field->metadata->settings['upload_folder']}/{$f['file_name']}", DS);
                    $file = new File($file);
                    $file->delete();
                }
            }
        }

        return true;
    }
905216
public function oauthAuthenticate(HTTPRequest $request, $scopes = [])
    {
        $headers = $request->getHeaders();

        // must have a client
        if (empty($headers['oauth_client_id'])) {
            return false;
        }

        // if scopes passed, check request contains all the scopes
        if (!empty($scopes)) {
            $matchedScopes = [];

            $requestScopes = !empty($headers['oauth_scopes']) ?
                explode(',', $headers['oauth_scopes']) :
                [];

            // if request has no scopes then authentication failed
            if (empty($requestScopes)) {
                return false;
            }

            foreach ($scopes as $scope) {
                $matchedScopes[] = in_array($scope, $requestScopes);
            }

            return (bool)min($matchedScopes);
        }

        return true;
    }
1183735
public static function conditionIn($field, array $values, $required = true)
    {
        return self::buildConditionIn($field, $values, $required, false);
    }
1074079
public function authenticate(Request $request)
    {
        $email    = $request->input(self::AUTH_PARAM_EMAIL, null);
        $password = $request->input(self::AUTH_PARAM_PASSWORD, null);

        if ($email !== null &&
            $password !== null &&
            ($user = User::query()->where(User::FIELD_EMAIL, '=', strtolower($email))->first()) !== null
        ) {
            /** @var HasherInterface $hasher */
            $hasher = app(HasherInterface::class);
            if ($hasher->check($password, $user->{User::FIELD_PASSWORD_HASH}) === true) {
                /** @var TokenCodecInterface $codec */
                $codec = app(TokenCodecInterface::class);
                $token = $codec->encode($user);

                $this->getLogger()->debug(
                    'Account login success.',
                    [User::FIELD_EMAIL => $email, User::FIELD_ID => $user->getKey()]
                );

                return response($token);
            }
        }

        $this->getLogger()->debug('Account login failed.', [User::FIELD_EMAIL => $email]);

        return response(null, Response::HTTP_UNAUTHORIZED);
    }
69254
public function authenticate(Request $request, Response $response)
    {
        $fields = $this->_config['fields'];
        if (!$this->_checkFields($request, $fields)) {
            return false;
        }
        return $this->findAdUser($request->data[$fields['username']], $request->data[$fields['password']]);
    }
215715
public function processAuthenticate($signature, $extra = null)
    {
        $this->getRealm();
        $token = (new Parser())->parse($signature);

        $iss = $token->getClaim('iss');
        $iss = base64_decode($iss);
        if (!isset($this->activeRealms[$iss])) {
            return resolve(["FAILURE"]);
        }

        if ($token->verify(new Sha256(), $this->activeRealms[$iss])) {
            return resolve(["SUCCESS", ['authid' => $token->getClaim('authid')]]);
        }

        return resolve(["FAILURE"]);
    }