]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/OpenIdService.php
Default OpenID display name set to standard value
[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         // If the token is not expired, refreshing isn't necessary
75         if ($this->isUnexpired($accessToken)) {
76             return true;
77         }
78
79         // Try to obtain refreshed access token
80         try {
81             $newAccessToken = $this->refreshAccessToken($accessToken);
82         } catch (\Exception $e) {
83             // Log out if an unknown problem arises
84             $this->actionLogout();
85             throw $e;
86         }
87
88         // If a token was obtained, update the access token, otherwise log out
89         if ($newAccessToken !== null) {
90             session()->put('openid_token', json_encode($newAccessToken));
91             return true;
92         } else {
93             $this->actionLogout();
94             return false;
95         }
96     }
97
98     /**
99      * Check whether an access token or OpenID token isn't expired.
100      */
101     protected function isUnexpired(AccessToken $accessToken): bool
102     {
103         $idToken = $accessToken->getIdToken();
104         
105         $accessTokenUnexpired = $accessToken->getExpires() && !$accessToken->hasExpired();
106         $idTokenUnexpired = !$idToken || !$idToken->isExpired(); 
107
108         return $accessTokenUnexpired && $idTokenUnexpired;
109     }
110
111     /**
112      * Generate an updated access token, through the associated refresh token.
113      * @throws Error
114      */
115     protected function refreshAccessToken(AccessToken $accessToken): ?AccessToken
116     {
117         // If no refresh token available, abort
118         if ($accessToken->getRefreshToken() === null) {
119             return null;
120         }
121
122         // ID token or access token is expired, we refresh it using the refresh token
123         try {
124             return $this->getProvider()->getAccessToken('refresh_token', [
125                 'refresh_token' => $accessToken->getRefreshToken(),
126             ]);
127         } catch (IdentityProviderException $e) {
128             // Refreshing failed
129             return null;
130         }
131     }
132
133     /**
134      * Process the Authorization response from the authorization server and
135      * return the matching, or new if registration active, user matched to
136      * the authorization server.
137      * Returns null if not authenticated.
138      * @throws Error
139      * @throws OpenIdException
140      * @throws ValidationError
141      * @throws JsonDebugException
142      * @throws UserRegistrationException
143      */
144     public function processAuthorizeResponse(?string $authorizationCode): ?User
145     {
146         $provider = $this->getProvider();
147
148         // Try to exchange authorization code for access token
149         $accessToken = $provider->getAccessToken('authorization_code', [
150             'code' => $authorizationCode,
151         ]);
152
153         return $this->processAccessTokenCallback($accessToken);
154     }
155
156     /**
157      * Do the required actions to log a user out.
158      */
159     protected function actionLogout()
160     {
161         auth()->logout();
162         session()->invalidate();
163     }
164
165     /**
166      * Load the underlying OpenID Connect Provider.
167      * @throws Error
168      * @throws Exception
169      */
170     protected function getProvider(): OpenIDConnectProvider
171     {
172         // Setup settings
173         $settings = $this->config['openid'];
174         $overrides = $this->config['openid_overrides'] ?? [];
175
176         if ($overrides && is_string($overrides)) {
177             $overrides = json_decode($overrides, true);
178         }
179
180         $openIdSettings = $this->loadOpenIdDetails();
181         $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
182
183         // Setup services
184         $services = $this->loadOpenIdServices();
185         $overrides = $this->config['openid_services'] ?? [];
186
187         $services = array_replace_recursive($services, $overrides);
188
189         return new OpenIDConnectProvider($settings, $services);
190     }
191
192     /**
193      * Load services utilized by the OpenID Connect provider.
194      */
195     protected function loadOpenIdServices(): array
196     {
197         return [
198             'signer' => new \Lcobucci\JWT\Signer\Rsa\Sha256(),
199         ];
200     }
201
202     /**
203      * Load dynamic service provider options required by the OpenID Connect provider.
204      */
205     protected function loadOpenIdDetails(): array
206     {
207         return [
208             'redirectUri' => url('/openid/redirect'),
209         ];
210     }
211
212     /**
213      * Calculate the display name
214      */
215     protected function getUserDisplayName(Token $token, string $defaultValue): string
216     {
217         $displayNameAttr = $this->config['display_name_attributes'];
218
219         $displayName = [];
220         foreach ($displayNameAttr as $dnAttr) {
221             $dnComponent = $token->getClaim($dnAttr, '');
222             if ($dnComponent !== '') {
223                 $displayName[] = $dnComponent;
224             }
225         }
226
227         if (count($displayName) == 0) {
228             $displayName = $defaultValue;
229         } else {
230             $displayName = implode(' ', $displayName);
231         }
232
233         return $displayName;
234     }
235
236     /**
237      * Get the value to use as the external id saved in BookStack
238      * used to link the user to an existing BookStack DB user.
239      */
240     protected function getExternalId(Token $token, string $defaultValue)
241     {
242         $userNameAttr = $this->config['external_id_attribute'];
243         if ($userNameAttr === null) {
244             return $defaultValue;
245         }
246
247         return $token->getClaim($userNameAttr, $defaultValue);
248     }
249
250     /**
251      * Extract the details of a user from an ID token.
252      */
253     protected function getUserDetails(Token $token): array
254     {
255         $email = null;
256         $emailAttr = $this->config['email_attribute'];
257         if ($token->hasClaim($emailAttr)) {
258             $email = $token->getClaim($emailAttr);
259         }
260
261         return [
262             'external_id' => $token->getClaim('sub'),
263             'email' => $email,
264             'name' => $this->getUserDisplayName($token, $email),
265         ];
266     }
267
268     /**
269      * Processes a received access token for a user. Login the user when
270      * they exist, optionally registering them automatically.
271      * @throws OpenIdException
272      * @throws JsonDebugException
273      * @throws UserRegistrationException
274      */
275     public function processAccessTokenCallback(AccessToken $accessToken): User
276     {
277         $userDetails = $this->getUserDetails($accessToken->getIdToken());
278         $isLoggedIn = auth()->check();
279
280         if ($this->config['dump_user_details']) {
281             throw new JsonDebugException($accessToken->jsonSerialize());
282         }
283
284         if ($userDetails['email'] === null) {
285             throw new OpenIdException(trans('errors.openid_no_email_address'));
286         }
287
288         if ($isLoggedIn) {
289             throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
290         }
291
292         $user = $this->getOrRegisterUser($userDetails);
293         if ($user === null) {
294             throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
295         }
296
297         auth()->login($user);
298         session()->put('openid_token', json_encode($accessToken));
299         return $user;
300     }
301 }