From 74cb1477bb921a2378ea22a552b71a48c11e0931 Mon Sep 17 00:00:00 2001 From: Marvin Borner Date: Fri, 20 Jul 2018 16:34:32 +0200 Subject: Better API (integrated oauth completely) --- infrastructure/Auth/LoginProxy.php | 126 +++++++++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 infrastructure/Auth/LoginProxy.php (limited to 'infrastructure/Auth/LoginProxy.php') diff --git a/infrastructure/Auth/LoginProxy.php b/infrastructure/Auth/LoginProxy.php new file mode 100644 index 0000000..11783f0 --- /dev/null +++ b/infrastructure/Auth/LoginProxy.php @@ -0,0 +1,126 @@ +userRepository = $userRepository; + + $this->apiConsumer = $app->make('apiconsumer'); + $this->auth = $app->make('auth'); + $this->cookie = $app->make('cookie'); + $this->db = $app->make('db'); + $this->request = $app->make('request'); + } + + /** + * Attempt to create an access token using user credentials + * + * @param string $email + * @param string $password + */ + public function attemptLogin($email, $password) + { + $user = $this->userRepository->getWhere('email', $email)->first(); + + if (!is_null($user)) { + return $this->proxy('password', [ + 'username' => $email, + 'password' => $password + ]); + } + + throw new InvalidCredentialsException(); + } + + /** + * Attempt to refresh the access token used a refresh token that + * has been saved in a cookie + */ + public function attemptRefresh() + { + $refreshToken = $this->request->cookie(self::REFRESH_TOKEN); + + return $this->proxy('refresh_token', [ + 'refresh_token' => $refreshToken + ]); + } + + /** + * Proxy a request to the OAuth server. + * + * @param string $grantType what type of grant type should be proxied + * @param array $data the data to send to the server + */ + public function proxy($grantType, array $data = []) + { + $data = array_merge($data, [ + 'client_id' => env('PASSWORD_CLIENT_ID'), + 'client_secret' => env('PASSWORD_CLIENT_SECRET'), + 'grant_type' => $grantType + ]); + + $response = $this->apiConsumer->post('/oauth/token', $data); + + if (!$response->isSuccessful()) { + throw new InvalidCredentialsException(); + } + + $data = json_decode($response->getContent()); + + // Create a refresh token cookie + $this->cookie->queue( + self::REFRESH_TOKEN, + $data->refresh_token, + 864000, // 10 days + null, + null, + false, + true // HttpOnly + ); + + return [ + 'access_token' => $data->access_token, + 'expires_in' => $data->expires_in + ]; + } + + /** + * Logs out the user. We revoke access token and refresh token. + * Also instruct the client to forget the refresh cookie. + */ + public function logout() + { + $accessToken = $this->auth->user()->token(); + + $refreshToken = $this->db + ->table('oauth_refresh_tokens') + ->where('access_token_id', $accessToken->id) + ->update([ + 'revoked' => true + ]); + + $accessToken->revoke(); + + $this->cookie->queue($this->cookie->forget(self::REFRESH_TOKEN)); + } +} -- cgit v1.2.3