Do a remote call.
@param $request The Request instance
@param $isLogin Boolean whether this request is a login request or not
@return The Response instance
189950
protected function doRemoteCall(Request $request, $isLogin) {
    // initially login, if no cookie is set
    $cookyJar = $this->client->getCookieJar();
    if (!$isLogin && sizeof($cookyJar->getAllCookies()) == 0) {
      $response = $this->doLogin();
    }

    // do the request
    $request->setResponseFormat('json');
    $this->client->resetParameters();
    $this->client->setParameterPost('controller', $request->getSender());
    $this->client->setParameterPost('context', $request->getContext());
    $this->client->setParameterPost('action', $request->getAction());
    $this->client->setParameterPost('request_format', $request->getFormat());
    $this->client->setParameterPost('response_format', $request->getResponseFormat());
    $this->client->setParameterPost($request->getValues());
    try {
      $httpResponse = $this->client->request();
    }
    catch (\Exception $ex) {
      self::$logger->error("Error in remote call to ".$url.":\n".$ex, __FILE__);
      throw new \RuntimeException("Error in remote call to ".$url.": ".$ex->getMessage());
    }

    // deserialize the response
    $responseData = json_decode($httpResponse->getBody(), true);
    $response = new ControllerMessage('', '', '', $responseData);
    $response->setFormat('json');
    $formatter = ObjectFactory::getInstance('formatter');
    $formatter->deserialize($response);

    // handle errors
    if (!$response->getValue('success'))
    {
      $errorMsg = $response->getValue('errorMsg');
      // if the session expired, try to relogin
      if (strpos('Authorization failed', $errorMsg) === 0 && !$isLogin) {
        $this->doLogin();
      }
      $url = $this->client->getUri();
      self::$logger->error("Error in remote call to ".$url.": ".$errorMsg."\n".$response->toString(), __FILE__);
      throw new \RuntimeException("Error in remote call: $errorMsg");
    }
    return $response;
  }
61496
public static function checkAuthentication($redirect = true)
    {
        if(static::isAuthenticated()) {
            return;
        }

        if ($redirect) {
            Http\Server::getInstance()->redirect(RouteCollection::getInstance()->get('login')->getUri());
        } else {
            throw new LoginException();
        }
    }
1344887
public function postLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required',
            'password'             => 'required',
        ]);

        // 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.
        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);

        if (\Taki::attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

        // 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.
        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return redirect($this->loginPath())
                ->withInput($request->only($this->loginUsername(), 'remember'))
                ->withErrors([
                    $this->loginUsername() => $this->getFailedLoginMessage(),
        ]);
    }
617239
private function login(ServerRequestInterface $request)
    {
        //Check header
        $authorization = $this->parseHeader($request->getHeaderLine('Authorization'));

        if (!$authorization) {
            return false;
        }

        //Check the user
        if (!isset($this->users[$authorization['username']])) {
            return false;
        }

        if ($this->users[$authorization['username']] !== $authorization['password']) {
            return false;
        }

        return $authorization['username'];
    }
601651
public function loginPage(ServerRequestInterface $request, ?Tree $tree): ResponseInterface
    {
        // Already logged in?
        if (Auth::check()) {
            $ged = $tree !== null ? $tree->name() : '';

            return redirect(route('user-page', ['ged' => $ged]));
        }

        $error    = $request->get('error', '');
        $url      = $request->get('url', '');
        $username = $request->get('username', '');

        $title = I18N::translate('Sign in');

        switch (Site::getPreference('WELCOME_TEXT_AUTH_MODE')) {
            case 1:
            default:
                $welcome = I18N::translate('Anyone with a user account can access this website.');
                break;
            case 2:
                $welcome = I18N::translate('You need to be an authorized user to access this website.');
                break;
            case 3:
                $welcome = I18N::translate('You need to be a family member to access this website.');
                break;
            case 4:
                $welcome = Site::getPreference('WELCOME_TEXT_AUTH_MODE_' . WT_LOCALE);
                break;
        }

        if (Site::getPreference('USE_REGISTRATION_MODULE') === '1') {
            $welcome .= ' ' . I18N::translate('You can apply for an account using the link below.');
        }

        $can_register = Site::getPreference('USE_REGISTRATION_MODULE') === '1';

        return $this->viewResponse('login-page', [
            'can_register' => $can_register,
            'error'        => $error,
            'title'        => $title,
            'url'          => $url,
            'username'     => $username,
            'welcome'      => $welcome,
        ]);
    }
1098013
public function postLogin(Request $request)
    {

        $this->validate($request, ['username' => 'required|min:3|max:255', 'password' => 'required',]);

        $credentials = $request->only('username', 'password');
        $credentials[ 'enabled' ] = 1;

        if (Auth::attempt($credentials, $request->has('remember'))) {
            return redirect()->intended($this->getRedirectUrl());
        } else {
            return redirect(route('login'))->withInput($request->except(['password']))
                                           ->withErrors([$this->getFailedLoginMessage()]);
        }

    }
942184
public function provideSessionInfo( WebRequest $request ) {

		# Loop through user names given by all remote sources. First hit, which
		# matches a usable local user name, will be used for our SessionInfo then.
		foreach ( $this->remoteUserNames as $remoteUserName ) {

			if ( $remoteUserName instanceof Closure ) {
				$remoteUserName = call_user_func( $remoteUserName );
			}

			# Keep info about remote-to-local user name processing for logging and
			# and later for provider metadata.
			$metadata = [ 'remoteUserName' => (string)$remoteUserName ];

			if ( !is_string( $remoteUserName ) || empty( $remoteUserName ) ) {
				$this->logger->warning(
					"Can't login remote user '{remoteUserName}' automatically. " .
					"Given remote user name is not of type string or empty.",
					$metadata
				);
				continue;
			}

			# Process each given remote user name if needed, e.g. strip NTLM domain,
			# replace characters, rewrite to another username or even blacklist it by
			# returning false. This can be used by the wiki administrator to adjust
			# this SessionProvider to his specific needs.
			$filteredUserName = $remoteUserName;
			if ( !Hooks::run( static::HOOKNAME, [ &$filteredUserName ] ) ) {
				$metadata[ 'filteredUserName' ] = $filteredUserName;
				$this->logger->warning(
					"Can't login remote user '{remoteUserName}' automatically. " .
					"Blocked this user when applying filter to '{filteredUserName}'.",
					$metadata
				);
				continue;
			}
			$metadata[ 'filteredUserName' ] = (string)$filteredUserName;

			if ( !is_string( $filteredUserName ) || empty( $filteredUserName ) ) {
				$this->logger->warning(
					"Can't login remote user '{remoteUserName}' automatically. " .
					"Filtered remote user name '{filteredUserName}' is not of " .
					"type string or empty.",
					$metadata
				);
				continue;
			}

			# Create a UserInfo (and User) object by given user name. The factory
			# method will take care of correct validation of user names. It will also
			# canonicalize it (e.g. transform the first letter to uppercase).
			#
			# An exception gets thrown when the given user name is not 'usable' as an
			# user name for the wiki, either blacklisted or contains invalid characters
			# or is an ip address.
			#
			# @see User::getCanonicalName()
			# @see User::isUsableName()
			# @see Title::newFromText()
			try {
				$userInfo = UserInfo::newFromName( $filteredUserName, true );
			} catch ( InvalidArgumentException $e ) {
				$metadata[ 'exception' ] = $e;
				$this->logger->warning(
					"Can't login remote user '{remoteUserName}' automatically. " .
					"Filtered name '{filteredUserName}' is not usable as an " .
					"user name in MediaWiki.: {exception}",
					$metadata
				);
				continue;
			}
			$metadata[ 'userId' ] = $userInfo->getId();
			$metadata[ 'canonicalUserName' ] = $userInfo->getName();

			# Let our parent class find a valid SessionInfo.
			$sessionInfo = parent::provideSessionInfo( $request );

			# Our parent class provided a session info, but the `$wgGroupPermission` for
			# creating user accounts was changed while using this extension. This leds
			# to a behaviour where a new user won't be created automatically even if the
			# wiki administrator enabled (auto) account creation by setting the specific
			# group permission `createaccount` or `autocreateaccount` to `true`.
			#
			# This happens in rare circurmstances only: The global permission forbids
			# account creation. A new user requests the wiki and a specific session is
			# getting created (by our parent). Then the `AuthManager` permits further
			# account creation attempts due to global permission by marking this session
			# as blacklistet. This blacklist info is stored inside the session itself.
			# Now when the wiki admin changes the global account creation permission to
			# `true` and the new user wants to access the wiki, then his account is not
			# created automatically due to this blacklist marking inside his current
			# session, identified by our parent class. Hence we throw this session away
			# in these rare cases (We could manipulate the session itself and delete that
			# `AuthManager::AutoCreateBlacklist` key instead, but that would look like
			# real hacked code inside this method).
			#
			# @see AuthManager::AutoCreateBlacklist
			# @see AuthManager::autoCreateUser()
			if ( $sessionInfo && $userInfo->getUser()->isAnon() ) {
				$anon = $userInfo->getUser();
				$permissions = $anon->getGroupPermissions( $anon->getEffectiveGroups() );
				if (
					in_array( 'autocreateaccount', $permissions, true )
					|| in_array( 'createaccount', $permissions, true )
				) {
					$this->logger->warning(
						"Renew session due to global permission change " .
						"in (auto) creating new users."
					);
					$sessionInfo = null;
				}
			}

			# If our parent provides a session info, it could be from an old request
			# where the old remote user name doesn't match the one used for the current
			# request. This happens when the client switched the user remotely (because
			# he has access to two different accounts at the remote source). Therefore
			# we have to mark the local authentication part (the cookie, because we
			# inherit from `CookieSessionProvider`) and compare it against the current
			# request. We use the `filteredUserName` instead of `remoteuserName` for the
			# comparison, because the wiki admin could have mapped two differing remote
			# user names to the same local username with an according filter. For the
			# marking itself we have to overwrite some inherited methods.
			#
			# @see self::getCookieDataToExport()
			# @see self::persistSession()
			if ( $sessionInfo ) {
				$prefix = $this->cookieOptions[ 'prefix' ];
				$old = $this->getCookie( $request, 'RemoteToken', $prefix );
				if ( $old !== $filteredUserName ) {
					$this->logger->warning(
						"Renew local session due to remote session change."
					);
					$sessionInfo = null;
				}
			}

			# Our parent class couldn't provide any info. This means we can create a
			# new session with our identified user.
			if ( !$sessionInfo ) {
				$sessionInfo = new SessionInfo( $this->priority, [
					'provider' => $this,
					'userInfo' => $userInfo
					]
				);
				$this->callUserLoggedInHook = true;
			}

			# The current session identifies an anonymous user, therefore we have to
			# use the forceUse flag to set our identified user. If we are configured
			# to forbid user switching, force the usage of our identified user too.
			if ( !$sessionInfo->getUserInfo() || !$sessionInfo->getUserInfo()->getId()
				|| ( !$this->switchUser && $sessionInfo->getUserInfo()->getId() !== $userInfo->getId() ) ) {
				$sessionInfo = new SessionInfo( $sessionInfo->getPriority(), [
					'copyFrom' => $sessionInfo,
					'userInfo' => $userInfo,
					'forceUse' => true
					]
				);
				$this->callUserLoggedInHook = true;
			}

			# Store info about user in the provider metadata.
			$metadata[ 'canonicalUserNameUsed' ] = $sessionInfo->getUserInfo()->getName();
			$sessionInfo = new SessionInfo( $sessionInfo->getPriority(), [
				'copyFrom' => $sessionInfo,
				'metadata' => $metadata
				]
			);

			return $sessionInfo;
		}

		# We didn't identified anything, so let other SessionProviders do their work.
		return null;
	}
864900
protected function sendLoginResponse(Request $request)
    {
        $user = auth()->guard($this->getGuard())->user();

        $twofactor = $user->getTwoFactor();
        $totpStatus = $twofactor['totp']['enabled'] ?? false;
        $phoneStatus = $twofactor['phone']['enabled'] ?? false;

        $request->session()->regenerate();
        $this->clearLoginAttempts($request);

        // Enforce TwoFactor authentication
        if ($totpStatus || $phoneStatus) {
            $this->processLogout($request);

            $request->session()->put('cortex.auth.twofactor', ['user_id' => $user->getKey(), 'remember' => $request->filled('remember'), 'totp' => $totpStatus, 'phone' => $phoneStatus]);

            $route = $totpStatus
                ? route('adminarea.verification.phone.verify')
                : route('adminarea.verification.phone.request');

            return intend([
                'url' => $route,
                'with' => ['warning' => trans('cortex/auth::messages.verification.twofactor.totp.required')],
            ]);
        }

        return intend([
            'intended' => route('adminarea.home'),
            'with' => ['success' => trans('cortex/auth::messages.auth.login')],
        ]);
    }
992678
public function login(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string|email|max:240',
            'password'        => 'required|string|min:4|max:240',
        ]);

        // 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);
        }

        // make sure the account has been activated
        if (!User::where($this->username(), input($this->username()))
            ->whereNotNull('confirmed_at')
            ->first()) {
            $this->logLogin($request, 'inactive');

            return $this->sendFailedLoginResponse($request,
                'Please activate your account before trying to login.');
        }

        // try to login
        if (Auth::attempt($request->only([$this->username(), 'password']),
            input('remember', false))) {
            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);

        $this->logLogin($request, 'invalid');

        return $this->sendFailedLoginResponse($request);
    }
1150612
public function loginAction($request)
    {
        $data = $request->get('data');
        $userModel = new ModelUser();
        $validUser = $userModel->validateLogin($data['email'], $data['password']);

        if (!$validUser) {
            $this->setMessage('danger', 'Not valid user / password combination');
            return $this->redirect(url('login'));
        }

        $this->session()->set('user', $userModel->record);
        $this->sessionClearMessages();
        return $this->redirect('/');
    }
801614
public function onLogoutSuccess(Request $request)
    {
        $resourceOwnerToken = $this->session->get('claroline.oauth.resource_owner_token');
        $redirectUrl = $this->router->generate('claro_index', [], true);
        if (!empty($resourceOwnerToken)) {
            try {
                $resourceOwnerName = str_replace('_', '', ucwords($resourceOwnerToken['resourceOwnerName'], '_'));
                $resourceOwner = $this->resourceOwnerFactory->{'get'.$resourceOwnerName.'ResourceOwner'}();
                if ($resourceOwnerName === 'Office365' || $resourceOwnerName === 'WindowsLive') {
                    return $resourceOwner->logout($redirectUrl);
                }
                $resourceOwner->revokeToken($resourceOwnerToken['token']);
            } catch (AuthenticationException $e) {
                // Do nothing
            }
        }

        return new RedirectResponse($redirectUrl);
    }
325880
public function handleLogin(Login $request)
    {
        // Set the auth data
        $userData = [
            'username' => $request->get('username'),
            'password' => $request->get('password'),
        ];

        // Log in successful
        if (auth()->attempt($userData, $request->get('remember', false))) {
            event(new UserLoggedIn(auth()->user()));

            return redirect()
                ->intended(route('home'))
                ->with('message', 'You have been logged in.');
        }

        // Login failed
        return redirect(route('auth.login'))
            ->with('errors', ['Your username or password was incorrect.']);
    }
736553
public function login($username, $password, \Espo\Entities\AuthToken $authToken = null, $params = [], $request)
    {
        if (!$password) return;

        $isPortal = !empty($params['isPortal']);

        if ($authToken) {
            return $this->loginByToken($username, $authToken);
        }

        if ($isPortal) {
            $useLdapAuthForPortalUser = $this->getUtils()->getOption('portalUserLdapAuth');
            if (!$useLdapAuthForPortalUser) {
                return parent::login($username, $password, $authToken, $params, $request);
            }
        }

        $ldapClient = $this->getLdapClient();

        /* Login LDAP system user (ldapUsername, ldapPassword) */
        try {
            $ldapClient->bind();
        } catch (\Exception $e) {
            $options = $this->getUtils()->getLdapClientOptions();
            $GLOBALS['log']->error('LDAP: Could not connect to LDAP server ['.$options['host'].'], details: ' . $e->getMessage());

            $adminUser = $this->adminLogin($username, $password);
            if (!isset($adminUser)) {
                return null;
            }

            $GLOBALS['log']->info('LDAP: Administrator ['.$username.'] was logged in by Espo method.');
        }

        if (!isset($adminUser)) {
            try {
                $userDn = $this->findLdapUserDnByUsername($username);
            } catch (\Exception $e) {
                $GLOBALS['log']->error('Error while finding DN for ['.$username.'], details: ' . $e->getMessage() . '.');
            }

            if (!isset($userDn)) {
                $GLOBALS['log']->error('LDAP: Authentication failed for user ['.$username.'], details: user is not found.');

                $adminUser = $this->adminLogin($username, $password);
                if (!isset($adminUser)) {
                    return null;
                }

                $GLOBALS['log']->info('LDAP: Administrator ['.$username.'] was logged in by Espo method.');
            }

            $GLOBALS['log']->debug('User ['.$username.'] is found with this DN ['.$userDn.'].');

            try {
                $ldapClient->bind($userDn, $password);
            } catch (\Exception $e) {
                $GLOBALS['log']->error('LDAP: Authentication failed for user ['.$username.'], details: ' . $e->getMessage());
                return null;
            }
        }

        $user = $this->getEntityManager()->getRepository('User')->findOne([
            'whereClause' => [
                'userName' => $username,
                'type!=' => ['api', 'system']
            ]
        ]);

        if (!isset($user) && $this->getUtils()->getOption('createEspoUser')) {
            $userData = $ldapClient->getEntry($userDn);
            $user = $this->createUser($userData, $isPortal);
        }

        return $user;
    }
574634
public function execute($request)
    {
        $logger = $GLOBALS['logger'];

        try {
            parent::execute($request);
        } catch(AuthenticationException $ex) {
            $logger->error('Unauthorized attempt to access resource, being redirected to home page', array($ex->getMessage()));
            $this->_handleUnauthenticatedAccess();
            $this->_response->send();
        }
    }
359711
private function login(ServerRequestInterface $request, &$username)
    {
        //Check header
        $authorization = self::parseAuthorizationHeader($request->getHeaderLine('Authorization'));

        if (!$authorization) {
            return false;
        }

        //Check whether user exists
        if (!isset($this->users[$authorization['username']])) {
            return false;
        }

        $username = $authorization['username'];

        //Check authentication
        return $this->checkAuthentication($authorization, $request->getMethod(), $this->users[$username]);
    }
304161
public function postLogin(LoginRequest $request)
    {
        $inputs = $request->except('_token','rememberme');

        $rememberme = $request->get('rememberme');

        $attemp = Auth::attempt($inputs, !!$rememberme);

        if (!$attemp) {
            $request->session()->flash('error', trans('auth.failed'));
            return Redirect::back();
        }

        return Redirect::intended('/');

    }
827562
private function sendRequest($request)
    {
        $response = $this->webclient->send($request);
        if (!$this->isLoggedIn($response)) {
            $this->webLogin();
            $response = $this->webclient->send($request);
        }

        if ($response->getStatusCode() == 500) {
            throw new YouHostingException("Unknown YouHosting Error");
        }

        return $response;
    }