Send an auth request and return the json data as a stdClass object

@param string $username
@param string $password
@param array  $scopes
@param array  $client
@param string $grant_type
@param bool   $is_email
@return \stdClass
188624
public function authenticate($username, $password, array $scopes = [], array $client = [], $grant_type = 'password', $is_email = false)
	{
		$scope = implode(',', $scopes);

		$request_data = [
			'password'      => $password,
			'client_id'     => $client['client_id'],
			'client_secret' => $client['client_secret'],
			'grant_type'    => $grant_type,
			'scope'         => $scope,
		];

		if ($is_email) {
			$request_data['email'] = $username;
		} else {
			$request_data['username'] = $username;
		}

		$response = $this->post($this->oauthUrl(), $request_data)->getJson();

		// If this was a successful auth, set the access token
		if (isset($response->access_token)) {
			$this->access_tokens[$username] = $response->access_token;
		}

		return $response;
	}
1192069
public static function getPDO($dsn, $username, $password, $settings = ['attributes' => []])
    {
        // if not set self pdo object property or pdo set as null
        if (!isset(self::$PDO) || (self::$PDO !== null)) {
            self::$PDO = new self($dsn, $username, $password, $settings); // set class pdo property with new connection
        }

        // return class property object
        return self::$PDO;
    }
355895
protected function createPayload(Oauth\Client\Account $client, array $scope = [])
    {
        // token to encrypt
        $expires = time() + $this->config[ 'token' ][ 'lifetime' ];

        $id = Token::generate(40, Token::ALPHAHASH_STRING);
        $payload = [
            'id'         => $id,
            // the internal id of the token
            'jti'        => $id,
            // a unique token identifier for the token (JWT ID)
            'iss'        => $this->config[ 'issuer' ],
            // the id of the server who issued the token (Issuer)
            'aud'        => $client->id,
            // the id of the client who requested the token (Audience)
            'sub'        => ($this->user->offsetExists('id') ? $this->user->offsetGet('id') : null),
            // the id of the user for which the token was released (Subject)
            'exp'        => $expires,
            'iat'        => time(),
            'token_type' => $this->config[ 'token' ][ 'type' ],
            'scope'      => empty($scope) ? null : implode(' ', $scope),
        ];

        if ($client->offsetExists('metadata')) {
            if (is_array($client->metadata)) {
                $payload = array_merge($client->metadata, $payload);
            }
        }

        return $payload;
    }
1300572
function user_login_webservice($username, $password) {
        global $CFG, $DB;
        // special web service login
        if ($user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id))) {
            return validate_internal_user_password($user, $password);
        }
        return false;
    }
1145103
public function request(Request $request)
    {
        $user = User::whereEmail($request->email)->firstOrFail();
        $user->sendResetPasswordNotification($this->broker()->createToken($user), $request);

        return response()->json('Password request successful', 200);
    }
1297963
private function getAuthHeaders($email, $password, $clientConfig)
    {
        if (!$email || !$password) {
            return [];
        }

        if (!isset($clientConfig['oauth2']['enabled']) || !$clientConfig['oauth2']['enabled']) {
            return [
                'X-API-Email-Enc'    => base64_encode($email),
                'X-API-Password-Enc' => base64_encode($password),
                'X-API-Email'        => $email,
                'X-API-Password'     => $password
            ];
        }

        $oauth2Config = $clientConfig['oauth2'];
        $accessToken = array_key_exists('access_token', $oauth2Config) ? $oauth2Config["access_token"] : "";
        if (empty($accessToken)) {
            $accessToken = $this->getAccessToken($email, $password, $clientConfig);
        }

        if (!$accessToken) {
            throw new Exception('Cannot find/create valid token');
        }

        return [
            'Authorization' => "Bearer {$accessToken}"
        ];
    }
556141
public function requestClientCredentials($options = array()) {
        $options = array_merge(array(
            'scope' => '',
        ), $options);

        $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array(
            'client_id' => $this->getClientId(),
            'client_secret' => $this->getClientSecret(),
            'grant_type' => 'client_credentials',
            'scope' => $options['scope'],
        ));
        $result = $res->getBody();

        $token = null;
        if ($result && $result = json_decode($result, true)) {
            if (!empty($result['error'])) {
                throw new Exception($result['error_description']);
            }

            if (!empty($result['access_token'])) {
                $this->accessToken = $token = $result['access_token'];
            }
        }

        if (empty($token)) {
            throw new InvalidTokenException('token not available.');
        }

        return $token;
    }
1180068
public function login($username, $password, $domain = null)
	{
		//Logger::log("Logging in");

		$details = array(
			'action' => 'login',
			'lgname' => $username,
			'lgpassword' => $password,
			'format' => 'json'
		);

		// If $domain is provided, set the corresponding detail in the request information array
		if (is_string($domain)) {
			$details['lgdomain'] = $domain;
		}

		// Send the login request
		$response = $this->session->post($this->api, array(), $details);
		// Check if we got an API result or the API doc page (invalid request)
		if (strpos($response->body, "This is an auto-generated MediaWiki API documentation page") !== false) {
			$this->error = array();
			$this->error['login'] = 'The API could not understand the first login request';
			return false;
		}

		$loginResult = json_decode($response->body);

		if ($this->debugMode) {
			echo "Login request:\n";
			print_r($details);
			echo "Login request response:\n";
			print_r($loginResult);
		}

		if (isset($loginResult->login->result) && $loginResult->login->result == 'NeedToken') {
			//Logger::log("Sending token {$loginResult->login->token}");
			$details['lgtoken'] = strtolower(trim($loginResult->login->token));

			// Send the confirm token request
			$loginResult = $this->session->post($this->api, array(), $details)->body;

			// Check if we got an API result or the API doc page (invalid request)
			if (strpos($loginResult, "This is an auto-generated MediaWiki API documentation page") !== false) {
				$this->error = array();
				$this->error['login'] = 'The API could not understand the confirm token request';
				return false;
			}

			$loginResult = json_decode($loginResult);

			if ($this->debugMode) {
				echo "Confirm token request:\n";
				print_r($details);
				echo "Confirm token response:\n";
				print_r($loginResult);
			}

			if ($loginResult->login->result != 'Success') {
				// Some more comprehensive error checking
				$this->error = array();
				switch ($loginResult->login->result) {
					case 'NotExists':
						$this->error['login'] = 'The username does not exist';
						break;
					default:
						$this->error['login'] = 'The API result was: ' . $loginResult->login->result;
						break;
				}
				return false;
			}
		}

		//Logger::log("Logged in");
		return true;
	}
133496
static function loginUser( $login, $password, $authenticationMatch = false )
    {
        $http = eZHTTPTool::instance();
        $db = eZDB::instance();

        if ( $authenticationMatch === false )
            $authenticationMatch = eZUser::authenticationMatch();

        $loginEscaped = $db->escapeString( $login );
        $passwordEscaped = $db->escapeString( $password );

        $loginArray = array();
        if ( $authenticationMatch & eZUser::AUTHENTICATE_LOGIN )
            $loginArray[] = "login='$loginEscaped'";
        if ( $authenticationMatch & eZUser::AUTHENTICATE_EMAIL )
            $loginArray[] = "email='$loginEscaped'";
        if ( count( $loginArray ) == 0 )
            $loginArray[] = "login='$loginEscaped'";
        $loginText = implode( ' OR ', $loginArray );

        $contentObjectStatus = eZContentObject::STATUS_PUBLISHED;

        $ini = eZINI::instance();
        $textFileIni = eZINI::instance( 'textfile.ini' );
        $databaseName = $db->databaseName();
        // if mysql
        if ( $databaseName === 'mysql' )
        {
            $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login
                      FROM ezuser, ezcontentobject
                      WHERE ( $loginText ) AND
                        ezcontentobject.status='$contentObjectStatus' AND
                        ( ezcontentobject.id=contentobject_id OR ( password_hash_type=4 AND ( $loginText ) AND password_hash=PASSWORD('$passwordEscaped') ) )";
        }
        else
        {
            $query = "SELECT contentobject_id, password_hash, password_hash_type, email, login
                      FROM ezuser, ezcontentobject
                      WHERE ( $loginText ) AND
                            ezcontentobject.status='$contentObjectStatus' AND
                            ezcontentobject.id=contentobject_id";
        }

        $users = $db->arrayQuery( $query );
        $exists = false;
        if ( count( $users ) >= 1 )
        {
            foreach ( $users as $userRow )
            {
                $userID = $userRow['contentobject_id'];
                $hashType = $userRow['password_hash_type'];
                $hash = $userRow['password_hash'];
                $exists = eZUser::authenticateHash( $userRow['login'], $password, eZUser::site(),
                                                    $hashType,
                                                    $hash );

                // If hash type is MySql
                if ( $hashType == eZUser::PASSWORD_HASH_MYSQL and $databaseName === 'mysql' )
                {
                    $queryMysqlUser = "SELECT contentobject_id, password_hash, password_hash_type, email, login
                                       FROM ezuser, ezcontentobject
                                       WHERE ezcontentobject.status='$contentObjectStatus' AND
                                             password_hash_type=4 AND ( $loginText ) AND password_hash=PASSWORD('$passwordEscaped') ";
                    $mysqlUsers = $db->arrayQuery( $queryMysqlUser );
                    if ( count( $mysqlUsers ) >= 1 )
                        $exists = true;
                }

                 // If current user has been disabled after a few failed login attempts.
                $canLogin = eZUser::isEnabledAfterFailedLogin( $userID );

                if ( $exists )
                {
                    eZDebugSetting::writeDebug( 'kernel-user', eZUser::createHash( $userRow['login'], $password, eZUser::site(),
                                                                                   $hashType ), "check hash" );
                    eZDebugSetting::writeDebug( 'kernel-user', $hash, "stored hash" );

                    // We should store userID for warning message.
                    $GLOBALS['eZFailedLoginAttemptUserID'] = $userID;

                    $userSetting = eZUserSetting::fetch( $userID );
                    $isEnabled = $userSetting->attribute( "is_enabled" );
                    if ( $hashType != eZUser::hashType() and
                         strtolower( $ini->variable( 'UserSettings', 'UpdateHash' ) ) == 'true' )
                    {
                        $hashType = eZUser::hashType();
                        $hash = eZUser::createHash( $login, $password, eZUser::site(),
                                                    $hashType );
                        $db->query( "UPDATE ezuser SET password_hash='$hash', password_hash_type='$hashType' WHERE contentobject_id='$userID'" );
                    }
                    break;
                }
            }
        }
        if ( $exists and $isEnabled and $canLogin )
        {
            eZDebugSetting::writeDebug( 'kernel-user', $userRow, 'user row' );
            $user = new eZUser( $userRow );
            eZDebugSetting::writeDebug( 'kernel-user', $user, 'user' );
            $userID = $user->attribute( 'contentobject_id' );

            eZUser::updateLastVisit( $userID );
            eZUser::setCurrentlyLoggedInUser( $user, $userID );

            // Reset number of failed login attempts
            eZUser::setFailedLoginAttempts( $userID, 0 );

            return $user;
        }
        else if ( $textFileIni->variable( 'TextFileSettings', 'TextFileEnabled' ) == "true" )
        {
            $fileName =  $textFileIni->variable( 'TextFileSettings', 'FileName' );
            $filePath =  $textFileIni->variable( 'TextFileSettings', 'FilePath' );
            $defaultUserPlacement = $ini->variable( "UserSettings", "DefaultUserPlacement" );
            $separator = $textFileIni->variable( "TextFileSettings", "FileFieldSeparator" );
            $loginColumnNr = $textFileIni->variable( "TextFileSettings", "LoginAttribute" );
            $passwordColumnNr = $textFileIni->variable( "TextFileSettings", "PasswordAttribute" );
            $emailColumnNr = $textFileIni->variable( "TextFileSettings", "EmailAttribute" );
            $lastNameColumnNr = $textFileIni->variable( "TextFileSettings", "LastNameAttribute" );
            $firstNameColumnNr = $textFileIni->variable( "TextFileSettings", "FirstNameAttribute" );
            if ( $textFileIni->hasVariable( 'TextFileSettings', 'DefaultUserGroupType' ) )
            {
                $UserGroupType =  $textFileIni->variable( 'TextFileSettings', 'DefaultUserGroupType' );
                $UserGroup = $textFileIni->variable( 'TextFileSettings', 'DefaultUserGroup' );
            }

            if ( $UserGroupType != null )
            {
                if ( $UserGroupType == "name" )
                {
                    $groupName = $UserGroup;
                    $groupQuery = "SELECT ezcontentobject_tree.node_id
                                       FROM ezcontentobject, ezcontentobject_tree
                                       WHERE ezcontentobject.name='$groupName'
                                       AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                    $groupObject = $db->arrayQuery( $groupQuery );

                    if ( count( $groupObject ) > 0  )
                    {
                        $defaultUserPlacement = $groupObject[0]['node_id'];
                    }
                }
                else if ( $UserGroupType == "id" )
                {
                    $groupID = $UserGroup;
                    $groupQuery = "SELECT ezcontentobject_tree.node_id
                                           FROM ezcontentobject, ezcontentobject_tree
                                           WHERE ezcontentobject.id='$groupID'
                                           AND ezcontentobject.id=ezcontentobject_tree.contentobject_id";
                    $groupObject = $db->arrayQuery( $groupQuery );

                    if ( count( $groupObject ) > 0  )
                    {
                        $defaultUserPlacement = $groupObject[0]['node_id'];
                    }
                }
            }

            if ( $filePath != "root" and $filePath != null  )
                $fileName = $filePath . "/" . $fileName;

            if ( file_exists( $fileName ) )
                $handle = fopen ( $fileName, "r");
            else
            {
                // Increase number of failed login attempts.
                if ( isset( $userID ) )
                    eZUser::setFailedLoginAttempts( $userID );

                return false;
            }

            while ( !feof( $handle ) )
            {
                $line = trim( fgets( $handle, 4096 ) );

                if ( $line === '' )
                    continue;

                if ( $separator == "tab" )
                    $userArray = explode( "\t", $line );
                else
                    $userArray = explode( $separator, $line );

                $uid = $userArray[$loginColumnNr-1];
                $email = $userArray[$emailColumnNr-1];
                $pass = $userArray[$passwordColumnNr-1];
                $firstName = $userArray[ $firstNameColumnNr-1];
                $lastName = $userArray[$lastNameColumnNr-1];
                if ( $login == $uid )
                {
                    if ( trim( $pass ) == $password )
                    {
                        $createNewUser = true;
                        $existUser = eZUser::fetchByName( $login );
                        if ( $existUser != null )
                        {
                            $createNewUser = false;
                        }
                        if ( $createNewUser )
                        {
                            $userClassID = $ini->variable( "UserSettings", "UserClassID" );
                            $userCreatorID = $ini->variable( "UserSettings", "UserCreatorID" );
                            $defaultSectionID = $ini->variable( "UserSettings", "DefaultSectionID" );

                            $remoteID = "TextFile_" . $login;

                            $db->begin();

                            // The content object may already exist if this process has failed once before, before the eZUser object was created.
                            // Therefore we try to fetch the eZContentObject before instantiating it.
                            $contentObject = eZContentObject::fetchByRemoteID( $remoteID );
                            if ( !is_object( $contentObject ) )
                            {
                                $class = eZContentClass::fetch( $userClassID );
                                $contentObject = $class->instantiate( $userCreatorID, $defaultSectionID );
                            }

                            $contentObject->setAttribute( 'remote_id', $remoteID );
                            $contentObject->store();

                            $contentObjectID = $contentObject->attribute( 'id' );
                            $userID = $contentObjectID;
                            $nodeAssignment = eZNodeAssignment::create( array( 'contentobject_id' => $contentObjectID,
                                                                               'contentobject_version' => 1,
                                                                               'parent_node' => $defaultUserPlacement,
                                                                               'is_main' => 1 ) );
                            $nodeAssignment->store();
                            $version = $contentObject->version( 1 );
                            $version->setAttribute( 'modified', time() );
                            $version->setAttribute( 'status', eZContentObjectVersion::STATUS_DRAFT );
                            $version->store();

                            $contentObjectID = $contentObject->attribute( 'id' );
                            $contentObjectAttributes = $version->contentObjectAttributes();

                            $contentObjectAttributes[0]->setAttribute( 'data_text', $firstName );
                            $contentObjectAttributes[0]->store();

                            $contentObjectAttributes[1]->setAttribute( 'data_text', $lastName );
                            $contentObjectAttributes[1]->store();

                            $user = eZUser::create( $userID );
                            $user->setAttribute( 'login', $login );
                            $user->setAttribute( 'email', $email );
                            $user->setAttribute( 'password_hash', "" );
                            $user->setAttribute( 'password_hash_type', self::PASSWORD_HASH_EMPTY );
                            $user->store();

                            eZUser::updateLastVisit( $userID );
                            eZUser::setCurrentlyLoggedInUser( $user, $userID );

                            // Reset number of failed login attempts
                            eZUser::setFailedLoginAttempts( $userID, 0 );

                            $operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $contentObjectID,
                                                                                                         'version' => 1 ) );

                            $db->commit();

                            return $user;
                        }
                        else
                        {
                            $db->begin();

                            // Update user information
                            $userID = $existUser->attribute( 'contentobject_id' );
                            $contentObject = eZContentObject::fetch( $userID );

                            $parentNodeID = $contentObject->attribute( 'main_parent_node_id' );
                            $currentVersion = $contentObject->attribute( 'current_version' );

                            $version = $contentObject->attribute( 'current' );
                            $contentObjectAttributes = $version->contentObjectAttributes();

                            $contentObjectAttributes[0]->setAttribute( 'data_text', $firstName );
                            $contentObjectAttributes[0]->store();

                            $contentObjectAttributes[1]->setAttribute( 'data_text', $lastName );
                            $contentObjectAttributes[1]->store();

                            $existUser = eZUser::fetch(  $userID );
                            $existUser->setAttribute('email', $email );
                            $existUser->setAttribute('password_hash', "" );
                            $existUser->setAttribute('password_hash_type', self::PASSWORD_HASH_EMPTY );
                            $existUser->store();

                            if ( $defaultUserPlacement != $parentNodeID )
                            {
                                $newVersion = $contentObject->createNewVersion();
                                $newVersion->assignToNode( $defaultUserPlacement, 1 );
                                $newVersion->removeAssignment( $parentNodeID );
                                $newVersionNr = $newVersion->attribute( 'version' );
                                $operationResult = eZOperationHandler::execute( 'content', 'publish', array( 'object_id' => $userID,
                                                                                                             'version' => $newVersionNr ) );
                            }

                            eZUser::updateLastVisit( $userID );
                            eZUser::setCurrentlyLoggedInUser( $existUser, $userID );

                            // Reset number of failed login attempts
                            eZUser::setFailedLoginAttempts( $userID, 0 );

                            $db->commit();

                            return $existUser;
                        }
                    }
                    else
                    {
                        // Increase number of failed login attempts.
                        if ( isset( $userID ) )
                            eZUser::setFailedLoginAttempts( $userID );

                        return false;
                    }
                }
            }
            fclose( $handle );
        }
        // Increase number of failed login attempts.
        if ( isset( $userID ) )
            eZUser::setFailedLoginAttempts( $userID );

        return false;
    }
1134984
public static function getAccessToken(
        ContextInterface $context,
        array $scopes = null,
        array $options = []
    ): AccessToken
	{
		$formParams = [
			'grant_type' => 'client_credentials',
			'client_id' => $context->getClientId(),
			'client_secret' => $context->getClientSecret(),
		];

		if ($scopes !== null) {
			$formParams['scope'] = implode(',', $scopes);
		}

        $client = SumUp::getClient($options);

		$response = $client->request(
			'POST',
			self::OAUTH_TOKEN,
			[
				'form_params' => $formParams,
			]);

		$code = $response->getStatusCode();
		if ($code !== 200) {
			$message = " Request code: $code \n Message: " . $response->getReasonPhrase();
			throw new BadRequestException($message);
		}

		$body = json_decode($response->getBody()->getContents(), true);
		$token_params = [
			$body['access_token'],
			$body['token_type'],
			$body['expires_in'],
		];

		if (isset($body['scope'])) {
			$token_params[] = $body['scope'];
		}

		return new AccessToken(...$token_params);
	}
669075
function user_password($username,$password){
        if ($username==NULL){ return (false); }
        if ($password==NULL){ return (false); }
        if (!$this->_bind){ return (false); }
        if (!$this->_use_ssl){ echo ("FATAL: SSL must be configured on your webserver and enabled in the class to set passwords."); exit(); }
        
        $user=$this->user_info($username,array("cn"));
        if ($user[0]["dn"]==NULL){ return (false); }
        $user_dn=$user[0]["dn"];
                
        $add=array();
        $add["unicodePwd"][0]=$this->encode_password($password);
        
        $result=ldap_mod_replace($this->_conn,$user_dn,$add);
        if ($result==false){ return (false); }
        
        return (true);
    }
915643
public function authenticate($username, $password, $type = self :: AUTH_ANY) {

		if(false === is_string($username)) {
            return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($username)), E_USER_ERROR);
        }

        if(false === is_string($password)) {
            return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($password)), E_USER_ERROR);
        }

        if(false === defined($type)) {
			return trigger_error(sprintf('Argument 3 passed to %s() is not a valid authentication type', __METHOD__), E_USER_ERROR);
        }

		$this -> options[CURLOPT_USERPWD]  = sprintf('%s:%s', $username, $password);
		$this -> options[CURLOPT_HTTPAUTH] = constant($type);

		return $this;
	}
34884
public function createClient(Client $client, $password)
    {
        $data = $client->toArray();
        $data['password_confirm'] = $data['password'] = $password;
        $data['send_email'] = 0;
        $data['submit'] = 'Save';

        $response = $this->post('/en/client/add', $data);

        if ($response->getStatusCode() == 200) {
            $error = $this->getBetween((string)$response->getBody(), '<ul class="errors">', '</ul>');
            $error = $this->getBetween($error, '<li>', '</li>');
            throw new YouHostingException("Unable to create profile: " . $error);
        }

        $response = $this->get($response->getHeader('Location'));

        $client->id = $this->getBetweenReverse((string)$response->getBody(), '/en/client/view/id/', '">' . $client->email);
        return $client;
    }
661173
protected function requestAccessToken($grantType = 'client_credential')
    {
        $result = $this->httpGet(self::WECHAT_ACCESS_TOKEN_PREFIX, [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'grant_type' => $grantType
        ]);
        return isset($result['access_token']) ? $result : false;
    }
565527
private function auth($db, $username, $password, array $array = [])
    {
        //Prepare urls for different clients
        $urlCommon = $this->setApiEndPoint($this->commonEndPoint);
        $urlActions = $this->setApiEndPoint($this->objectEndPoint);

        //Assign clients by type
        $this->common = $this->getClient($urlCommon);
        $this->object = $this->getClient($urlActions);

        $this->uid = $this->common->authenticate($db, $username, $password, $array);

        if (!is_int($this->uid)) {
            if (is_array($this->uid) && array_key_exists('faultCode', $this->uid))
                throw new OdooException($this->uid['faultCode']);
            else
                throw new OdooException('Unsuccessful Authorization');
        }

    }
805793
public function getUserByEmail($email, $baseDn = null, $scope = Ldap::SEARCH_SCOPE_SUB, $attributes = [])
    {
        return $this->search(
            sprintf('(&(objectClass=user)(mail=%s))', AbstractFilter::escapeValue($email)),
            $baseDn,
            $scope,
            $attributes
        );
    }
1190852
public function authentication($username, $password)
    {
        $endpoint = sprintf('authentication?username=%s', urlencode($username));
        $parameters['value'] = $password;
        return $this->apiClient->callEndpoint(
            $endpoint,
            $parameters,
            null,
            HttpMethod::REQUEST_POST
        );
    }