Complete the client credentials grant

@return array

@throws
3947
public function completeFlow()
    {
        $selfClient = app('selfClient');
        // Get the required params
        if (is_null($selfClient)) {
            throw new Exception\InvalidClientException();
        }

        // Validate client ID and client secret
        $client = $this->server->getClientStorage()->get(
            $selfClient->id,
            $selfClient->secret,
            null,
            $this->getIdentifier()
        );

        if (($client instanceof ClientEntity) === false) {
            $this->server->getEventEmitter()->emit(new Event\ClientAuthenticationFailedEvent($this->server->getRequest()));
            throw new Exception\InvalidClientException();
        }

        // Create a new session
        $session = new SessionEntity($this->server);
        $session->setOwner('client', $client->getId());
        $session->associateClient($client);

        // Generate an access token
        $accessToken = new AccessTokenEntity($this->server);
        $accessToken->setId(SecureKey::generate());
        $accessToken->setExpireTime($this->getAccessTokenTTL() + time());

        foreach ($session->getScopes() as $scope) {
            $accessToken->associateScope($scope);
        }

        // Save everything
        $session->save();
        $accessToken->setSession($session);
        $accessToken->save();

        $oauthClient = new GenericProvider([
            'clientId'                => $selfClient->id,    // The client ID assigned to you by the provider
            'clientSecret'            => $selfClient->secret,   // The client password assigned to you by the provider
            'redirectUri'             => null,
            'urlAuthorize'            => null,
            'urlAccessToken'          => null,
            'urlResourceOwnerDetails' => null
        ]);
        $accessToken = new AccessToken(['access_token' => $accessToken->getId(), 'expires' => $accessToken->getExpireTime()]);
        return function ($method, $url, $options = []) use ($oauthClient, $accessToken) {
            return $oauthClient->getAuthenticatedRequest($method, $url, $accessToken, $options);
        };
    }
202287
public function connect($credentials = [])
    {
        if ($diff = array_diff(array_keys($this->settings), array_keys($credentials))) {
            throw new \Exception("Missing credentials, the following fields are missing ".implode('/', $diff));
        }

        $this->settings = array_merge($this->settings, $credentials);

        if (isset($this->settings['port']) === false) {
            $this->settings['port'] = 143;
        }

        $this->conn = @imap_open('{'.$this->settings['server'].':'.$this->settings['port'].'/notls}',
            $this->settings['username'], $this->settings['password']);

        if ($this->conn == false) {
            throw new \Exception("Could not connect or authorize to ".$this->settings['server'].':'.$this->settings['port']);
        }

        return ($this->conn != null);
    }
858859
public function getCredentials()
    {
        $result = $this->getSettingsByGroup('credentials');
        // No separate key for now.
        $result[Tag::EmailOnWarning] = $result[Tag::EmailOnError];
        return $result;
    }
1120704
protected function createAuthData()
    {
        return [
            'clientId' => $this->config['client_id'],
            'apiKey' => $this->config['api_key'],
            'requestTime' => time(),
            'sha' => sha1($this->config['api_key'] . $this->config['client_id'] . $this->config['api_secret'])
        ];
    }
384848
private function getToken()
    {
        $data = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->userId,
            'client_secret' => $this->secret,
        );

        $requestResult = $this->sendRequest('oauth/access_token', 'POST', $data, false);

        if ($requestResult->http_code !== 200) {
            return false;
        }

        $this->refreshToken = 0;
        $this->token = $requestResult->data->access_token;

        $hashName = md5($this->userId . '::' . $this->secret);
        /** Save token to storage */
        $this->tokenStorage->set($hashName, $this->token);

        return true;
    }
153394
public function getData(): array
    {
        return [
            $this->serverOriginScheme,
            $this->serverOriginHost,
            $this->serverOriginPort,
            $this->isPreFlightCanBeCached,
            $this->preFlightCacheMaxAge,
            $this->isForceAddMethods,
            $this->isForceAddHeaders,
            $this->isUseCredentials,
            $this->areAllOriginsAllowed,
            $this->allowedOrigins,
            $this->areAllMethodsAllowed,
            $this->allowedLcMethods,
            $this->allowedMethodsList,
            $this->areAllHeadersAllowed,
            $this->allowedLcHeaders,
            $this->allowedHeadersList,
            $this->exposedHeadersList,
            $this->isCheckHost,
        ];
    }
517447
public function getCredentials()
    {
        $secret = $this->getSecret();

        if (!isset($secret['username']) || !isset($secret['password'])) {
            throw new CredentialError('Unrecognized credential secret');
        }

        return parent::getCredentials();
    }
1205497
protected function getVerifyCredentialsCallback()
    {
        if (is_null($this->callback) || !is_callable($this->callback)) {
            throw new Exception\ServerErrorException('Null or non-callable callback set on Password grant');
        }

        return $this->callback;
    }
1340883
public function getPayload()
    {
        $payload = array();
        if ($this->incomingAllow == true) {
            $incoming = array();
            $incoming['allow'] = true;
            $payload['incoming'] = $incoming;
        }

        if ($this->outgoingApplicationSid) {
            $outgoing = array();
            $outgoing['application_sid'] = $this->outgoingApplicationSid;

            if ($this->outgoingApplicationParams) {
                $outgoing['params'] = $this->outgoingApplicationParams;
            }

            $payload['outgoing'] = $outgoing;
        }

        if ($this->pushCredentialSid) {
            $payload['push_credential_sid'] = $this->pushCredentialSid;
        }

        if ($this->endpointId) {
            $payload['endpoint_id'] = $this->endpointId;
        }

        return $payload;
    }
987907
private function fetchAccessToken() {
        // Setup the params
        $params = [
            'client_id'     => $this->clientID,
            'client_secret' => $this->secret,
            'grant_type'    => 'authorization_code',
            'code'          => $this->requestToken
        ];

        if (isset($this->redirectURI)) {
            $params['redirect_uri'] = $this->redirectURI;
        }

        // Parse the cURL result
        $this->parseAccessToken(CURL::post($this->url, $params));
    }
980761
public function getRepositoryCredentials()
    {
        $endpoint = $this->vcs->runLocally('currentEndpoint');
        $user = $this->bash->runLocally('whoami');

        return $this->askQuestions('vcs', [
            'repository' => ['Where is your code located?', $endpoint],
            'username' => ['What is the username for it?', $user],
            'password' => 'And the password?',
        ]);
    }
218177
public function createCredentials()
    {
        $credentials = new Credentials();
        $credentials->setTransactor($this);
        $credentials->setCredentials(array(
            'providerId' => null,
            'providerGateId' => null,
            'providerGateKey' => null,
            'merchantId' => null,
            'merchantGateId' => null,
            'merchantGateKey' => null
        ));

        return $credentials;
    }
475790
protected function requestAppAccessToken()
    {
        $credentials = $this->authHelper->generateAppCredentials($this->apiKey, $this->apiSecret);

        $endpoint = '/oauth2/token';

        $url = $this->urlHelper->joinSlugs([$this->baseUrl, $endpoint]);

        $data = ['grant_type' => 'client_credentials'];

        $headers = [
            'Authorization' => 'Basic ' . $credentials,
            'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
        ];

        $response = $this->courier->post($url, $data, $headers)->toArray();

        return $response['access_token'];
    }
501438
protected function getPassThruParams()
    {

        if ($this->passThruParams !== null) {
            return $this->passThruParams;
        }

        $this->passThruParams = [];

        $all = Input::all();

        $filtered = array_except($all, ['sync','uploadedFile','folderName']);

        // Security check
        if (count($filtered) > 30) {
            throw new RuntimeException('Too many query params');
        }

        foreach ($filtered as $key=>$value) {
            $this->passThruParams[$key] = strip_tags($value);
        }

        return $this->passThruParams;

    }
920028
public function getAccessToken()
    {
        return $this->requestHandler->sendRequestAsync('POST', 'api/v4/oauth/access_token/')->then(
            function ($tokenValues) {
                parse_str($tokenValues, $tokenArray);
                $token = $tokenArray['oauth_token'];
                $tokenSecret = $tokenArray['oauth_token_secret'];
                $this->requestHandler->setAccessTokenCredentials($token, $tokenSecret);
                return $tokenArray;
            }
        );
    }
1313207
public function check()
	{
		if (isset($this->check)) {
			return $this->check;
		}
		
		try {
			Authorizer::validateAccessToken();
			$this->type = 'user';
			return $this->check = true;
		} catch (Exception $e) {}
		
		$client_id     = Request::input('client_id');
		$client_secret = Request::input('client_secret');
		if (!$client_id || !$client_secret) {
			return $this->check = false;
		}
		
		$client = $this->fetchClient($client_id, $client_secret);
		if (!$client) {
			return $this->check = false;
		}
		
		if (!in_array('client_id_secret', $client->grants())) {
			return $this->check = false;
		}
		
		$this->client = $client;
		$this->type = 'client';
		return $this->check = true;
	}
480306
public function clientCredentials($scope = 'public')
    {
        if (is_array($scope)) {
            $scope = implode(' ', $scope);
        }

        $token_response = $this->request(self::CLIENT_CREDENTIALS_TOKEN_ENDPOINT, array(
            'grant_type' => 'client_credentials',
            'scope' => $scope
        ), "POST", false);

        return $token_response;
    }