Authenticate the user attempting to sign in.

Events: BeforeAuth

@since 2.0.0
@access public

@param string $AuthenticationSchemeAlias Type of authentication we're attempting.
499009
public function Auth($AuthenticationSchemeAlias = 'default') {
      Gdn::Session()->EnsureTransientKey();
      
      $this->EventArguments['AuthenticationSchemeAlias'] = $AuthenticationSchemeAlias;
      $this->FireEvent('BeforeAuth');
      
      // Allow hijacking auth type
      $AuthenticationSchemeAlias = $this->EventArguments['AuthenticationSchemeAlias'];
      
      // Attempt to set Authenticator with requested method or fallback to default
      try {
         $Authenticator = Gdn::Authenticator()->AuthenticateWith($AuthenticationSchemeAlias);
      } catch (Exception $e) {
         $Authenticator = Gdn::Authenticator()->AuthenticateWith('default');
      }
      
      // Set up controller
      $this->View = 'auth/'.$Authenticator->GetAuthenticationSchemeAlias();
      $this->Form->SetModel($this->UserModel);
      $this->Form->AddHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default.

      $Target = $this->Target();

      $this->Form->AddHidden('Target', $Target);
      
      // Import authenticator data source
      switch ($Authenticator->DataSourceType()) {
         case Gdn_Authenticator::DATA_FORM:
            $Authenticator->FetchData($this->Form);
         break;
         
         case Gdn_Authenticator::DATA_REQUEST:
         case Gdn_Authenticator::DATA_COOKIE:
            $Authenticator->FetchData(Gdn::Request());
         break;
      }
      
      // By default, just render the view
      $Reaction = Gdn_Authenticator::REACT_RENDER;
      
      // Where are we in the process? Still need to gather (render view) or are we validating?
      $AuthenticationStep = $Authenticator->CurrentStep();
      
      switch ($AuthenticationStep) {
      
         // User is already logged in
         case Gdn_Authenticator::MODE_REPEAT:
            $Reaction = $Authenticator->RepeatResponse();
         break;
            
         // Not enough information to perform authentication, render input form
         case Gdn_Authenticator::MODE_GATHER:
            $this->AddJsFile('entry.js');
            $Reaction = $Authenticator->LoginResponse();
				if ($this->Form->IsPostBack())
					$this->Form->AddError('ErrorCredentials');
         break;
         
         // All information is present, authenticate
         case Gdn_Authenticator::MODE_VALIDATE:
            
            // Attempt to authenticate.
            try {
               if (!$this->Request->IsAuthenticatedPostBack()) {
                  $this->Form->AddError('Please try again.');
                  $Reaction = $Authenticator->FailedResponse();
               } else {
                  $AuthenticationResponse = $Authenticator->Authenticate();

                  $UserInfo = array();
                  $UserEventData = array_merge(array(
                     'UserID'    => Gdn::Session()->UserID,
                     'Payload'   => GetValue('HandshakeResponse', $Authenticator, FALSE)
                  ),$UserInfo);

                  Gdn::Authenticator()->Trigger($AuthenticationResponse, $UserEventData);
                  switch ($AuthenticationResponse) {
                     case Gdn_Authenticator::AUTH_PERMISSION:
                        $this->Form->AddError('ErrorPermission');
                        $Reaction = $Authenticator->FailedResponse();
                     break;

                     case Gdn_Authenticator::AUTH_DENIED:
                        $this->Form->AddError('ErrorCredentials');
                        $Reaction = $Authenticator->FailedResponse();
                     break;

                     case Gdn_Authenticator::AUTH_INSUFFICIENT:
                        // Unable to comply with auth request, more information is needed from user.
                        $this->Form->AddError('ErrorInsufficient');
                        $Reaction = $Authenticator->FailedResponse();
                     break;

                     case Gdn_Authenticator::AUTH_PARTIAL:
                        // Partial auth completed.
                        $Reaction = $Authenticator->PartialResponse();
                     break;

                     case Gdn_Authenticator::AUTH_SUCCESS:
                     default: 
                        // Full auth completed.
                        if ($AuthenticationResponse == Gdn_Authenticator::AUTH_SUCCESS)
                           $UserID = Gdn::Session()->UserID;
                        else
                           $UserID = $AuthenticationResponse;

                        header("X-Vanilla-Authenticated: yes");
                        header("X-Vanilla-TransientKey: ".Gdn::Session()->TransientKey());
                        $Reaction = $Authenticator->SuccessResponse();
                  }
               }
            } catch (Exception $Ex) {
               $this->Form->AddError($Ex);
            }
         break;
         
         case Gdn_Authenticator::MODE_NOAUTH:
            $Reaction = Gdn_Authenticator::REACT_REDIRECT;
         break;
      }
      
      switch ($Reaction) {
      
         case Gdn_Authenticator::REACT_RENDER:
            // Do nothing (render the view)
         break;
      
         case Gdn_Authenticator::REACT_EXIT:
            exit();
         break;
      
         case Gdn_Authenticator::REACT_REMOTE:
            // Let the authenticator handle generating output, using a blank slate
            $this->_DeliveryType= DELIVERY_TYPE_VIEW;
            
            exit;
         break;
         
         case Gdn_Authenticator::REACT_REDIRECT:
         default:
         
            if (is_string($Reaction))
               $Route = $Reaction;
            else
               $Route = $this->RedirectTo();
            
            if ($this->_RealDeliveryType != DELIVERY_TYPE_ALL && $this->_DeliveryType != DELIVERY_TYPE_ALL) {
               $this->RedirectUrl = Url($Route);
            } else {
               
               if ($Route !== FALSE) {
                  Redirect($Route);
               } else {
                  Redirect(Gdn::Router()->GetDestination('DefaultController'));
               }
            }
         break;
      }
      
      $this->SetData('SendWhere', "/entry/auth/{$AuthenticationSchemeAlias}");
      $this->Render();
   }
101550
public function createAuthenticatedToken(UserInterface $user, $providerKey)
    {
        $preAuthToken = $this->preAuthenticationTokenStorage->getToken();

        if (null === $preAuthToken) {
            throw new \RuntimeException('Unable to return an authenticated token since there is no pre authentication token.');
        }

        $authToken = new JWTUserToken($user->getRoles(), $user, $preAuthToken->getCredentials(), $providerKey);

        if ($this->dispatcher instanceof ContractsEventDispatcherInterface) {
            $this->dispatcher->dispatch(new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken), Events::JWT_AUTHENTICATED);
        } else {
            $this->dispatcher->dispatch(Events::JWT_AUTHENTICATED, new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken));
        }

        $this->preAuthenticationTokenStorage->setToken(null);

        return $authToken;
    }
148555
public function authenticate(array $credentials)
    {

        // Dirty hack so we can use in both User->Authenticator->authenticate() and \Nette\Security\User->login() methods
        // arrays with named keys instead of anonymous arrays.
        // Eg. $userAuthenticator->authenticate(['username' => $username, 'alwaysLogin' => true]); instead of
        // $userAuthenticator->authenticate([$username, null, null, null, true]);
        if (count($credentials) == 1 && isset($credentials[0]) && is_array($credentials[0])) {
            $credentials = $credentials[0];
        }

        $user = false;
        $source = null;
        $regenerateToken = null;
        $exception = null;
        $authenticators = $this->authenticatorManager->getAuthenticators();
        /** @var AuthenticatorInterface $authenticator */
        foreach ($authenticators as $authenticator) {
            try {
                $u = $authenticator->setCredentials($credentials)->authenticate();

                $regenerateToken = $authenticator->shouldRegenerateToken();

                if ($u !== null && $u !== false) {
                    $user = $u;
                    $source = $authenticator->getSource();
                    break;
                }
            } catch (RateLimitException $e) {
                $exception = $e;
                break;
            } catch (AuthenticationException $e) {
                if ($exception === null) {
                    $exception = $e;
                }
                continue;
            }
        }

        if ($user === false && $exception !== null) {
            throw $exception;
        }
        if ($user === false) {
            throw new AuthenticationException('', UserAuthenticator::IDENTITY_NOT_FOUND);
        }
        $this->emitter->emit(new UserSignInEvent($user, $source, $regenerateToken ?? true));

        $arr = $user->toArray();
        unset($arr[self::COLUMN_PASSWORD_HASH]);

        $groups = [];
        if ($user['role'] === UsersRepository::ROLE_ADMIN) {
            $userGroups = $user->related('admin_user_groups');
            foreach ($userGroups as $userGroup) {
                $groups[] = $userGroup->admin_group->name;
            }
        }

        return new Identity($user['id'], $groups, $arr);
    }
690147
public function auth() {

        try {
            $this->authResponse = $this->authAdapterInterface->authenticate();
        } catch (\Exception $ex) {
            throw $ex;
        }

        $message = $this->authResponse->getMessage();

        if ($message->getCode() == AuthResponse::AUTHRESPONSE_SUCCESS) {
            $this->session->set($message->getKeysession(), $message->getAttrsession());
        }

        return;
    }
827616
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        try {
            $event = new ApiAuthenticateEvent();

            if (null !== $token->getCredentials()) {
                $event->setUserName($token->getUsername());
                $event->setPassword($token->getCredentials());
                $this->dispatcher->dispatch(ApiAuthenticationEvents::AUTHENTICATE, $event);
            } elseif ($token->getUser() instanceof User) {
                //if we have no password then only way to authenticate is by api key
                $event->setApiKey($token->getUser()->getApiKey());
                $this->dispatcher->dispatch(ApiAuthenticationEvents::API_KEY_AUTHENTICATE, $event);
            }

            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException($e->getMessage());
        }

        return new UsernamePasswordToken(
            $user,
            $user->getPassword(),
            $providerKey,
            $user->getRoles()
        );
    }
900276
public function authenticate(array $credentials)
    {
        list($username, $password) = $credentials;
        $user = $this->users->findOneBy(array('username' => $username));

        if (!$user) {
            throw new NS\AuthenticationException("User not found.", self::IDENTITY_NOT_FOUND);
        }

        if ($user->password !== $this->calculateHash($password)) {
            throw new NS\AuthenticationException("Invalid password.", self::INVALID_CREDENTIAL);
        }

        $permissions = array();
        foreach ($user->getRole()->getPermissions() as $key => $per) {
            $permissions[$per->getResource()] = $per->getRead();
        }

        return new NS\Identity($user->id, $user->getRole()->getName(), array(
            'username' => $user->username,
            'email' => $user->email,
            'permissions' => $permissions,
        ));
    }
457718
public function authenticate($username, $token) {
        if (empty($username) || empty($token)) {
            throw new \ErrorException('No username or token supplied.');
        }
        
        $this->username = $username;
        $this->token = $token;
    }
66172
public void authenticate() {
    if (mAccount == null) {
      // Create account also performs authentication.
      createAccount();
    } else {
      mAccess = mAccount.authenticate();
      if (mRegion != null) {
        mAccess.setPreferredRegion(mRegion);
      }
    }
  }
95896
protected static function authenticate() :void {
		// if we did not authenticate before
		if(!self::$_account) {
			// search for an enabled account with that session key and a non expired session
			$account = \Models\Accounts::getFirstEnabledWithNonExpiredSession(
				// the session key
				Cook::get(Config::get('security', 'cookie'))
			);
			// if the cookie session key doesn't match any existing account session, we deny access
			$account ?: 
				self::refuse(
					'Your session is no longer valid', 
					403, true);
			// if the stored key and dynamically generated mismatch, we deny access
			$account->hasMatchingDynamicKey() ?: 
				self::refuse(
					'Your signature has changed since your last visit, please log-in again', 
					403, true);
			// if account has expired, we deny access
			!$account->hasItsValidityExpired() ?:
				self::refuse(
					"Your account has expired, it was valid until {$account->get('account_expiration_date')}", 
					403, true);
			// update our credentials
			self::$_account = $account;
			// set access as granted
			self::$_granted = true;
		}	
	}
886352
protected function useAssertCredentials($userEmail = '')
    {
        $serviceJsonUrl = array_get($this->config, 'service.file', '');

        if (empty($serviceJsonUrl)) {
            return false;
        }

        $this->client->setAuthConfig($serviceJsonUrl);
        
        if (! empty($userEmail)) {
            $this->client->setSubject($userEmail);
        }

        return true;
    }
323194
public function setAuthenticated($authenticated)
    {
        // make sure the metaevent is only sent when changing from
        // not-authenticate to authenticated
        if ($authenticated && !$this->authenticated) {
            // metaevent
            $this->getRealm()->publishMeta('wamp.metaevent.session.on_join', [$this->getMetaInfo()]);
        }
        parent::setAuthenticated($authenticated);

    }
149292
public function getUser($credentials, UserProviderInterface $userProvider): ?UserInterface
    {
        $token = $this->userProvider->getDecodedToken($credentials['jwt']);
        $clientKey = $token->iss;

        if (!$clientKey) {
            throw new AuthenticationException(
                \sprintf('API Key "%s" does not exist.', $credentials['jwt'])
            );
        }

        /** @var TenantInterface|UserInterface $user */
        $user = $this->userProvider->loadUserByUsername($clientKey);
        if (\property_exists($token, 'sub')) {
            // for some reasons, when webhooks are called - field sub is undefined
            $user->setUsername($token->sub);
        }

        return $user;
    }
130216
public function authenticate($method, $opts, $forceSetup = true) {
		if(!array_key_exists($method, self::$authProviders))
			throw new Client\Exception\AuthenticationFailed("Auth method '$method' is not registered");
		
		$this->setup();
		
		$this->authProvider = new self::$authProviders[$method]($this, $this->description->authentication->{$method}, $opts);
		
		$this->setup($forceSetup);
	}
1178996
@Override
    public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
        return authenticate(credentials);
    }
342772
public function beforeFilter()
    {
        $authentication = $this->getAuthenticationService();
        $provider = $authentication->getAuthenticationProvider();

        if ($provider === null ||
            $provider instanceof PersistenceInterface ||
            $provider instanceof StatelessInterface
        ) {
            return;
        }

        $this->dispatchEvent('Authentication.afterIdentify', [
            'provider' => $provider,
            'identity' => $this->getIdentity(),
            'service' => $authentication
        ], $this->getController());
    }
1007813
public function authenticate($auth = null)
    {
        if ($auth !== null) {
            $this->auth = $auth;
        }

        return $this->auth;
    }
1031176
protected function authenticateUser(Request $request, UserInterface $user, $resourceOwnerName, $accessToken, $fakeLogin = true)
    {
        try {
            $this->container->get('hwi_oauth.user_checker')->checkPreAuth($user);
            $this->container->get('hwi_oauth.user_checker')->checkPostAuth($user);
        } catch (AccountStatusException $e) {
            // Don't authenticate locked, disabled or expired users
            return;
        }

        $token = new OAuthToken($accessToken, $user->getRoles());
        $token->setResourceOwnerName($resourceOwnerName);
        $token->setUser($user);
        $token->setAuthenticated(true);

        $this->get('security.token_storage')->setToken($token);

        if ($fakeLogin) {
            // Since we're "faking" normal login, we need to throw our INTERACTIVE_LOGIN event manually
            $this->container->get('event_dispatcher')->dispatch(
                SecurityEvents::INTERACTIVE_LOGIN,
                new InteractiveLoginEvent($request, $token)
            );
        }
    }