diff --git a/src/Passport/PersonalAccessTokenFactory.php b/src/Passport/PersonalAccessTokenFactory.php new file mode 100644 index 0000000..739e07f --- /dev/null +++ b/src/Passport/PersonalAccessTokenFactory.php @@ -0,0 +1,133 @@ +jwt = $jwt; + $this->tokens = $tokens; + $this->server = $server; + $this->clients = $clients; + } + + /** + * Create a new personal access token. + * + * @param mixed $userId + * @param string $name + * @param array $scopes + * @return \Laravel\Passport\PersonalAccessTokenResult + */ + public function make($userId, $name, array $scopes = []) + { + $response = $this->dispatchRequestToAuthorizationServer( + $this->createRequest($this->clients->personalAccessClient(), $userId, $scopes) + ); + + $token = tap($this->findAccessToken($response), function ($token) use ($userId, $name) { + $token->forceFill([ + 'user_id' => $userId, + 'name' => $name, + ])->save(); + }); + + return new PersonalAccessTokenResult( + $response['access_token'], $token + ); + } + + /** + * Create a request instance for the given client. + * + * @param \Laravel\Passport\Client $client + * @param mixed $userId + * @param array $scopes + * @return \Zend\Diactoros\ServerRequest + */ + protected function createRequest($client, $userId, array $scopes) + { + return (new ServerRequest)->withParsedBody([ + 'grant_type' => 'personal_access', + 'client_id' => $client->id, + 'client_secret' => $client->secret, + 'user_id' => $userId, + 'scope' => implode(' ', $scopes), + ]); + } + + /** + * Dispatch the given request to the authorization server. + * + * @param \Zend\Diactoros\ServerRequest $request + * @return array + */ + protected function dispatchRequestToAuthorizationServer(ServerRequest $request) + { + return json_decode($this->server->respondToAccessTokenRequest( + $request, new Response + )->getBody()->__toString(), true); + } + + /** + * Get the access token instance for the parsed response. + * + * @param array $response + * @return Token + */ + protected function findAccessToken(array $response) + { + return $this->tokens->find( + $this->jwt->parse($response['access_token'])->getClaim('jti') + ); + } +}