Grant access to multiple sites

@param string $userLogin Username
@param string $access
@param array $idSites
@param array $optional
@return bool|object
@throws InvalidRequestException
971363
public function setUserAccess($userLogin, $access, $idSites, array $optional = [])
    {
        return $this->_request('UsersManager.setUserAccess', [
            'userLogin' => $userLogin,
            'access' => $access,
            'idSites' => $idSites,
        ], $optional);
    }
3095
public function authorize(
        array $options = [],
        callable $redirectHandler = null
    ) {
        $url = $this->getAuthorizationUrl($options);
        if ($redirectHandler) {
            return $redirectHandler($url, $this);
        }

        // @codeCoverageIgnoreStart
        header('Location: ' . $url);
        exit;
        // @codeCoverageIgnoreEnd
    }
483026
public function create($siteId, $userAgent = '', $requestIPAddress = '')
    {
        if (empty($siteId)) {
            throw new \Exception('Cannot create an instance without a site id');
        }

        $cookie = new Cookie();

        $userId = $cookie->getCookie(CookieNames::USER_ID);
        $userId = ! empty($userId) ? $userId : Uuid::v4();

        $payload = new Payload(new Cookie(), $siteId, $userId);

        $requestHeaders = [];

        $browserUserAgent = !empty($userAgent) ? $userAgent : Browser::getUserAgent();
        $browserIPAddress = !empty($requestIPAddress) ? $requestIPAddress : Browser::getRequestIPAddress();

        if (! empty($browserUserAgent)) {
            $requestHeaders['X-Original-User-Agent'] = $browserUserAgent;
        }

        if (! empty($browserIPAddress)) {
            $requestHeaders['X-Original-Request-IP-Address'] = $browserIPAddress;
        }

        $client = new Client([
            'base_uri' => API::ENDPOINT,
            RequestOptions::HEADERS => $requestHeaders,
            RequestOptions::HTTP_ERRORS => false,
            RequestOptions::VERIFY => false
        ]);

        return new Tracker($cookie, $payload, $client);
    }
1324583
public function passValidateCredentialsAndCreateAccessTokenResponse(
        string $userName,
        string $password,
        ClientInterface $client = null,
        bool $isScopeModified = false,
        array $scope = null,
        array $extraParameters = []
    ): ResponseInterface {
        assert($client !== null);

        if (($userIdentifier = $this->getIntegration()->validateUserId($userName, $password)) === null) {
            $this->logDebug('User not found with provided username and password.', ['username' => $userName]);
            throw new OAuthTokenBodyException(OAuthTokenBodyException::ERROR_INVALID_GRANT);
        }
        assert(is_int($userIdentifier) === true);
        $this->logInfo('User authenticated with provided username and password.', ['username' => $userName]);

        $changedScopeOrNull = $this->getIntegration()->verifyAllowedUserScope($userIdentifier, $scope);
        if ($changedScopeOrNull !== null) {
            assert(is_array($changedScopeOrNull));
            $isScopeModified = true;
            $scope           = $changedScopeOrNull;
        }

        $unsavedToken = $this->getIntegration()->createTokenInstance();
        $unsavedToken
            ->setClientIdentifier($client->getIdentifier())
            ->setScopeIdentifiers($scope)
            ->setUserIdentifier($userIdentifier);
        $isScopeModified === true ? $unsavedToken->setScopeModified() : $unsavedToken->setScopeUnmodified();

        $tokenExpiresIn = $this->setUpTokenValues($unsavedToken);
        $savedToken     = $this->getIntegration()->getTokenRepository()->createToken($unsavedToken);

        $response = $this->createBodyTokenResponse($savedToken, $tokenExpiresIn);

        return $response;
    }
1226586
public function loadByLoginName(string $login_name): ?UserInterface
    {
        if(array_key_exists($login_name, $this->users)){
            return $this->convertUser($this->users[$login_name]);
        }

        return null;
    }
1067837
public function userCanCreateInSite(AccountInterface $account, $type, Site $site)
    {
        // Damn this is ugly
        if ($this->manager->hasContext()) {
            $previous = $this->manager->getContext();
            $this->manager->setContext($site, new Request());
            $result = $this->userCanCreate($account, $type);
            $this->manager->setContext($previous, new Request());
        } else {
            $this->manager->setContext($site, new Request());
            $result = $this->userCanCreate($account, $type);
            $this->manager->dropContext();
        }
        return $result;
    }
1097492
public function login($options = []) {
		$options = Hash::merge($this->getConfig('login'), $options);
		$this->_handleUserBeingAlreadyLoggedIn($options);
		$entity = $this->UserTable->newEntity(null, ['validate' => false]);

		if ($this->_getRequest()->is('post')) {
			$user = $this->_beforeLogin($entity, $options);
			if ($user) {
				return $this->_afterLogin($user, $options);
			} else {
				$this->handleFlashAndRedirect('error', $options);
			}
		}

		if ($options['setEntity']) {
			$this->_setViewVar('userEntity', $entity);
		}

		return false;
	}
1293671
public function UserAdd(AuthUserAddRequest $argument,
                            $metadata = [], $options = [])
    {
        return $this->_simpleRequest('/etcdserverpb.Auth/UserAdd',
            $argument,
            ['\Etcdserverpb\AuthUserAddResponse', 'decode'],
            $metadata, $options);
    }
840910
public static function mapXDomainUser($domain_username, $domain, $uidNumber)
	{
		$db = \App::get('db');

		if (empty($domain))
		{
			return 0;
		}

		$query = 'SELECT domain_id FROM `#__xdomains` WHERE ' .
				 '#__xdomains.domain=' . $db->quote($domain);

		$db->setQuery($query);

		$result = $db->loadObject();

		if (empty($result))
		{
			$query = 'INSERT INTO `#__xdomains` (domain) VALUES (' . $db->quote($domain) . ')';

			$db->setQuery($query);

			$db->query();

			$domain_id = $db->insertid();
		}
		else
		{
			$domain_id = $result->domain_id;
		}

		$query = 'INSERT INTO `#__xdomain_users` (domain_id,domain_username,uidNumber) ' .
			' VALUES (' . $db->quote($domain_id) . ',' .
			$db->quote($domain_username) . ',' . $db->quote($uidNumber) . ')';

		$db->setQuery($query);

		if (!$db->query())
		{
			return false;
		}

		return true;
	}
743852
protected function authRedirect(RequestInterface $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;
        }

        $redirectTo = urlencode($request->getRequestTarget());

        header('HTTP/1.0 403 Forbidden');
        header('Location: '.$this->adminUrl('login?redirect_to='.$redirectTo));
        exit;
    }
1107918
public function init($options = [])
    {
        $auth = new Authentication();

        if (!$auth->check()) {
            $url = (isset($options['auth_login_url']))
            ? $options['auth_login_url']
            : '/auth/login';

            $this->redirect = $url;
        }
    }
1250385
public function loggedIn($user = null, $pass = null)
    {
        if ($this->hook('loggedIn', array($user, $pass)) !== false) {
            $this->app->redirect($this->getURL());
        }
    }
208526
public function authorize(RequestInterface $request)
    {
        if (!$area = $this->findMatchingArea($request)) {
            return $this;
        }

        if (!$this->user) {
            throw new AuthorizationException(sprintf('Access denied to area "%s". No authenticated user', $area->pattern()));
        }

        if (!$area->authorize($this->user, $request->clientIp())) {
            throw new AuthorizationException(sprintf('Access denied to area "%s". Authenticated user does not have access', $area->pattern()));
        }

        return $this;
    }
1109915
public function attempt(array $credentials = [], $login = true)
    {
        $user = $this->getProvider()->retrieveByCredentials($credentials);
        if ($user instanceof Authenticatable && $this->hasValidCredentials($user, $credentials)) {
            if ($login === true) {
                $this->login($user);
            }
            if (!($user instanceof SubjectContract)) {
                throw new InvalidTokenException("Unable to generate token");
            }
            return $this->generateToken($user);
        }
        return false;
    }
703623
public function linkAccount(Request $request, $ldapLogin, $server, $username = null)
    {
        $verifyPassword = false;
        $password = null;
        if (null === $username) {
            $verifyPassword = true;
            $username = $request->get('_username');
            $password = $request->get('_password');
        }
        $isAuthenticated = $this->authenticator->authenticate($username, $password, $verifyPassword);
        if ($isAuthenticated) {
            $user = $this->userManager->getUserByUsername($username);
            $this->createLdapUser($server, $ldapLogin, $user);

            return $this->registrationManager->loginUser($user, $request);
        } else {
            return ['error' => 'login_error'];
        }
    }
749032
public function login($userId, $guard = null)
    {
        $guard = $guard ?: config('auth.defaults.guard');

        $provider = Auth::guard($guard)->getProvider();

        $user = Str::contains($userId, '@')
                    ? $provider->retrieveByCredentials(['email' => $userId])
                    : $provider->retrieveById($userId);

        Auth::guard($guard)->login($user);
    }
1059874
public function post(Provider $provider, $userId, $requestScope, $requestUri, array $postBody, array $requestHeaders = [])
    {
        return $this->send($provider, $userId, $requestScope, Request::post($requestUri, $postBody, $requestHeaders));
    }