]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/OpenIdConnectService.php
Continued review of #2169
[bookstack] / app / Auth / Access / OpenIdConnectService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\OpenIdConnectException;
6 use BookStack\Exceptions\StoppedAuthenticationException;
7 use BookStack\Exceptions\UserRegistrationException;
8 use Exception;
9 use Lcobucci\JWT\Signer\Rsa\Sha256;
10 use Lcobucci\JWT\Token;
11 use OpenIDConnectClient\AccessToken;
12 use OpenIDConnectClient\OpenIDConnectProvider;
13
14 /**
15  * Class OpenIdConnectService
16  * Handles any app-specific OIDC tasks.
17  */
18 class OpenIdConnectService
19 {
20     protected $registrationService;
21     protected $loginService;
22     protected $config;
23
24     /**
25      * OpenIdService constructor.
26      */
27     public function __construct(RegistrationService $registrationService, LoginService $loginService)
28     {
29         $this->config = config('oidc');
30         $this->registrationService = $registrationService;
31         $this->loginService = $loginService;
32     }
33
34     /**
35      * Initiate an authorization flow.
36      * @return array{url: string, state: string}
37      */
38     public function login(): array
39     {
40         $provider = $this->getProvider();
41         return [
42             'url' => $provider->getAuthorizationUrl(),
43             'state' => $provider->getState(),
44         ];
45     }
46
47     /**
48      * Process the Authorization response from the authorization server and
49      * return the matching, or new if registration active, user matched to
50      * the authorization server.
51      * Returns null if not authenticated.
52      * @throws Exception
53      */
54     public function processAuthorizeResponse(?string $authorizationCode): ?User
55     {
56         $provider = $this->getProvider();
57
58         // Try to exchange authorization code for access token
59         $accessToken = $provider->getAccessToken('authorization_code', [
60             'code' => $authorizationCode,
61         ]);
62
63         return $this->processAccessTokenCallback($accessToken);
64     }
65
66     /**
67      * Load the underlying OpenID Connect Provider.
68      */
69     protected function getProvider(): OpenIDConnectProvider
70     {
71         // Setup settings
72         $settings = [
73             'clientId' => $this->config['client_id'],
74             'clientSecret' => $this->config['client_secret'],
75             'idTokenIssuer' => $this->config['issuer'],
76             'redirectUri' => url('/oidc/redirect'),
77             'urlAuthorize' => $this->config['authorization_endpoint'],
78             'urlAccessToken' => $this->config['token_endpoint'],
79             'urlResourceOwnerDetails' => null,
80             'publicKey' => $this->config['jwt_public_key'],
81             'scopes' => 'profile email',
82         ];
83
84         // Setup services
85         $services = [
86             'signer' => new Sha256(),
87         ];
88
89         return new OpenIDConnectProvider($settings, $services);
90     }
91
92     /**
93      * Calculate the display name
94      */
95     protected function getUserDisplayName(Token $token, string $defaultValue): string
96     {
97         $displayNameAttr = $this->config['display_name_claims'];
98
99         $displayName = [];
100         foreach ($displayNameAttr as $dnAttr) {
101             $dnComponent = $token->claims()->get($dnAttr, '');
102             if ($dnComponent !== '') {
103                 $displayName[] = $dnComponent;
104             }
105         }
106
107         if (count($displayName) == 0) {
108             $displayName[] = $defaultValue;
109         }
110
111         return implode(' ', $displayName);
112     }
113
114     /**
115      * Extract the details of a user from an ID token.
116      * @return array{name: string, email: string, external_id: string}
117      */
118     protected function getUserDetails(Token $token): array
119     {
120         $id = $token->claims()->get('sub');
121         return [
122             'external_id' => $id,
123             'email' => $token->claims()->get('email'),
124             'name' => $this->getUserDisplayName($token, $id),
125         ];
126     }
127
128     /**
129      * Processes a received access token for a user. Login the user when
130      * they exist, optionally registering them automatically.
131      * @throws OpenIdConnectException
132      * @throws JsonDebugException
133      * @throws UserRegistrationException
134      * @throws StoppedAuthenticationException
135      */
136     protected function processAccessTokenCallback(AccessToken $accessToken): User
137     {
138         $userDetails = $this->getUserDetails($accessToken->getIdToken());
139         $isLoggedIn = auth()->check();
140
141         if ($this->config['dump_user_details']) {
142             throw new JsonDebugException($accessToken->jsonSerialize());
143         }
144
145         if ($userDetails['email'] === null) {
146             throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
147         }
148
149         if ($isLoggedIn) {
150             throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
151         }
152
153         $user = $this->registrationService->findOrRegister(
154             $userDetails['name'], $userDetails['email'], $userDetails['external_id']
155         );
156
157         if ($user === null) {
158             throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
159         }
160
161         $this->loginService->login($user, 'oidc');
162         return $user;
163     }
164 }