]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/OpenIdService.php
2b536d492ffe659043c72e96c17c9a821aa6c1e9
[bookstack] / app / Auth / Access / OpenIdService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\OpenIdException;
6 use BookStack\Exceptions\UserRegistrationException;
7 use Exception;
8 use Lcobucci\JWT\Token;
9 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
10 use OpenIDConnectClient\AccessToken;
11 use OpenIDConnectClient\OpenIDConnectProvider;
12
13 /**
14  * Class OpenIdService
15  * Handles any app-specific OpenId tasks.
16  */
17 class OpenIdService extends ExternalAuthService
18 {
19     protected $config;
20
21     /**
22      * OpenIdService constructor.
23      */
24     public function __construct(RegistrationService $registrationService, User $user)
25     {
26         parent::__construct($registrationService, $user);
27         
28         $this->config = config('openid');
29     }
30
31     /**
32      * Initiate a authorization flow.
33      * @throws Error
34      */
35     public function login(): array
36     {
37         $provider = $this->getProvider();
38         return [
39             'url' => $provider->getAuthorizationUrl(),
40             'state' => $provider->getState(),
41         ];
42     }
43
44     /**
45      * Initiate a logout flow.
46      * @throws Error
47      */
48     public function logout(): array
49     {
50         $this->actionLogout();
51         $url = '/';
52         $id = null;
53
54         return ['url' => $url, 'id' => $id];
55     }
56
57     /**
58      * Refresh the currently logged in user.
59      * @throws Error
60      */
61     public function refresh(): bool
62     {
63         // Retrieve access token for current session
64         $json = session()->get('openid_token');
65
66         // If no access token was found, reject the refresh
67         if (!$json) {
68             $this->actionLogout();
69             return false;
70         }
71
72         $accessToken = new AccessToken(json_decode($json, true) ?? []);
73
74         // Check if both the access token and the ID token (if present) are unexpired
75         $idToken = $accessToken->getIdToken();
76         $accessTokenUnexpired = $accessToken->getExpires() && !$accessToken->hasExpired();
77         $idTokenUnexpired = !$idToken || !$idToken->isExpired(); 
78         if ($accessTokenUnexpired && $idTokenUnexpired) {
79             return true;
80         }
81
82         // If no refresh token available, logout
83         if ($accessToken->getRefreshToken() === null) {
84             $this->actionLogout();
85             return false;
86         }
87
88         // ID token or access token is expired, we refresh it using the refresh token
89         try {
90             $provider = $this->getProvider();
91
92             $accessToken = $provider->getAccessToken('refresh_token', [
93                 'refresh_token' => $accessToken->getRefreshToken(),
94             ]);
95         } catch (IdentityProviderException $e) {
96             // Refreshing failed, logout
97             $this->actionLogout();
98             return false;
99         } catch (\Exception $e) {
100             // Unknown error, logout and throw
101             $this->actionLogout();
102             throw $e;
103         }
104
105         // A valid token was obtained, we update the access token
106         session()->put('openid_token', json_encode($accessToken));
107
108         return true;
109     }
110
111     /**
112      * Process the Authorization response from the authorization server and
113      * return the matching, or new if registration active, user matched to
114      * the authorization server.
115      * Returns null if not authenticated.
116      * @throws Error
117      * @throws OpenIdException
118      * @throws ValidationError
119      * @throws JsonDebugException
120      * @throws UserRegistrationException
121      */
122     public function processAuthorizeResponse(?string $authorizationCode): ?User
123     {
124         $provider = $this->getProvider();
125
126         // Try to exchange authorization code for access token
127         $accessToken = $provider->getAccessToken('authorization_code', [
128             'code' => $authorizationCode,
129         ]);
130
131         return $this->processAccessTokenCallback($accessToken);
132     }
133
134     /**
135      * Do the required actions to log a user out.
136      */
137     protected function actionLogout()
138     {
139         auth()->logout();
140         session()->invalidate();
141     }
142
143     /**
144      * Load the underlying OpenID Connect Provider.
145      * @throws Error
146      * @throws Exception
147      */
148     protected function getProvider(): OpenIDConnectProvider
149     {
150         // Setup settings
151         $settings = $this->config['openid'];
152         $overrides = $this->config['openid_overrides'] ?? [];
153
154         if ($overrides && is_string($overrides)) {
155             $overrides = json_decode($overrides, true);
156         }
157
158         $openIdSettings = $this->loadOpenIdDetails();
159         $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
160
161         // Setup services
162         $services = $this->loadOpenIdServices();
163         $overrides = $this->config['openid_services'] ?? [];
164
165         $services = array_replace_recursive($services, $overrides);
166
167         return new OpenIDConnectProvider($settings, $services);
168     }
169
170     /**
171      * Load services utilized by the OpenID Connect provider.
172      */
173     protected function loadOpenIdServices(): array
174     {
175         return [
176             'signer' => new \Lcobucci\JWT\Signer\Rsa\Sha256(),
177         ];
178     }
179
180     /**
181      * Load dynamic service provider options required by the OpenID Connect provider.
182      */
183     protected function loadOpenIdDetails(): array
184     {
185         return [
186             'redirectUri' => url('/openid/redirect'),
187         ];
188     }
189
190     /**
191      * Calculate the display name
192      */
193     protected function getUserDisplayName(Token $token, string $defaultValue): string
194     {
195         $displayNameAttr = $this->config['display_name_attributes'];
196
197         $displayName = [];
198         foreach ($displayNameAttr as $dnAttr) {
199             $dnComponent = $token->getClaim($dnAttr, '');
200             if ($dnComponent !== '') {
201                 $displayName[] = $dnComponent;
202             }
203         }
204
205         if (count($displayName) == 0) {
206             $displayName = $defaultValue;
207         } else {
208             $displayName = implode(' ', $displayName);
209         }
210
211         return $displayName;
212     }
213
214     /**
215      * Get the value to use as the external id saved in BookStack
216      * used to link the user to an existing BookStack DB user.
217      */
218     protected function getExternalId(Token $token, string $defaultValue)
219     {
220         $userNameAttr = $this->config['external_id_attribute'];
221         if ($userNameAttr === null) {
222             return $defaultValue;
223         }
224
225         return $token->getClaim($userNameAttr, $defaultValue);
226     }
227
228     /**
229      * Extract the details of a user from an ID token.
230      */
231     protected function getUserDetails(Token $token): array
232     {
233         $email = null;
234         $emailAttr = $this->config['email_attribute'];
235         if ($token->hasClaim($emailAttr)) {
236             $email = $token->getClaim($emailAttr);
237         }
238
239         return [
240             'external_id' => $token->getClaim('sub'),
241             'email' => $email,
242             'name' => $this->getUserDisplayName($token, $email),
243         ];
244     }
245
246     /**
247      * Processes a received access token for a user. Login the user when
248      * they exist, optionally registering them automatically.
249      * @throws OpenIdException
250      * @throws JsonDebugException
251      * @throws UserRegistrationException
252      */
253     public function processAccessTokenCallback(AccessToken $accessToken): User
254     {
255         $userDetails = $this->getUserDetails($accessToken->getIdToken());
256         $isLoggedIn = auth()->check();
257
258         if ($this->config['dump_user_details']) {
259             throw new JsonDebugException($accessToken->jsonSerialize());
260         }
261
262         if ($userDetails['email'] === null) {
263             throw new OpenIdException(trans('errors.openid_no_email_address'));
264         }
265
266         if ($isLoggedIn) {
267             throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
268         }
269
270         $user = $this->getOrRegisterUser($userDetails);
271         if ($user === null) {
272             throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
273         }
274
275         auth()->login($user);
276         session()->put('openid_token', json_encode($accessToken));
277         return $user;
278     }
279 }