1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\SamlException;
8 use Illuminate\Support\Str;
9 use OneLogin\Saml2\Auth;
10 use OneLogin\Saml2\Error;
11 use OneLogin\Saml2\IdPMetadataParser;
12 use OneLogin\Saml2\ValidationError;
16 * Handles any app-specific SAML tasks.
18 class Saml2Service extends ExternalAuthService
26 * Saml2Service constructor.
28 public function __construct(UserRepo $userRepo, User $user)
30 $this->config = config('saml2');
31 $this->userRepo = $userRepo;
33 $this->enabled = config('saml2.enabled') === true;
37 * Initiate a login flow.
40 public function login(): array
42 $toolKit = $this->getToolkit();
43 $returnRoute = url('/saml2/acs');
45 'url' => $toolKit->login($returnRoute, [], false, false, true),
46 'id' => $toolKit->getLastRequestID(),
51 * Initiate a logout flow.
54 public function logout(): array
56 $toolKit = $this->getToolkit();
57 $returnRoute = url('/');
60 $url = $toolKit->logout($returnRoute, [], null, null, true);
61 $id = $toolKit->getLastRequestID();
62 } catch (Error $error) {
63 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
67 $this->actionLogout();
72 return ['url' => $url, 'id' => $id];
76 * Process the ACS response from the idp and return the
77 * matching, or new if registration active, user matched to the idp.
78 * Returns null if not authenticated.
80 * @throws SamlException
81 * @throws ValidationError
82 * @throws JsonDebugException
84 public function processAcsResponse(?string $requestId): ?User
86 if (is_null($requestId)) {
87 throw new SamlException(trans('errors.saml_invalid_response_id'));
90 $toolkit = $this->getToolkit();
91 $toolkit->processResponse($requestId);
92 $errors = $toolkit->getErrors();
94 if (!empty($errors)) {
96 'Invalid ACS Response: '.implode(', ', $errors)
100 if (!$toolkit->isAuthenticated()) {
104 $attrs = $toolkit->getAttributes();
105 $id = $toolkit->getNameId();
107 return $this->processLoginCallback($id, $attrs);
111 * Process a response for the single logout service.
114 public function processSlsResponse(?string $requestId): ?string
116 $toolkit = $this->getToolkit();
117 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
119 $errors = $toolkit->getErrors();
121 if (!empty($errors)) {
123 'Invalid SLS Response: '.implode(', ', $errors)
127 $this->actionLogout();
132 * Do the required actions to log a user out.
134 protected function actionLogout()
137 session()->invalidate();
141 * Get the metadata for this service provider.
144 public function metadata(): string
146 $toolKit = $this->getToolkit();
147 $settings = $toolKit->getSettings();
148 $metadata = $settings->getSPMetadata();
149 $errors = $settings->validateMetadata($metadata);
151 if (!empty($errors)) {
153 'Invalid SP metadata: '.implode(', ', $errors),
154 Error::METADATA_SP_INVALID
162 * Load the underlying Onelogin SAML2 toolkit.
166 protected function getToolkit(): Auth
168 $settings = $this->config['onelogin'];
169 $overrides = $this->config['onelogin_overrides'] ?? [];
171 if ($overrides && is_string($overrides)) {
172 $overrides = json_decode($overrides, true);
175 $metaDataSettings = [];
176 if ($this->config['autoload_from_metadata']) {
177 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
180 $spSettings = $this->loadOneloginServiceProviderDetails();
181 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
182 return new Auth($settings);
186 * Load dynamic service provider options required by the onelogin toolkit.
188 protected function loadOneloginServiceProviderDetails(): array
191 'entityId' => url('/saml2/metadata'),
192 'assertionConsumerService' => [
193 'url' => url('/saml2/acs'),
195 'singleLogoutService' => [
196 'url' => url('/saml2/sls')
201 'baseurl' => url('/saml2'),
207 * Check if groups should be synced.
209 protected function shouldSyncGroups(): bool
211 return $this->enabled && $this->config['user_to_groups'] !== false;
215 * Calculate the display name
217 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
219 $displayNameAttr = $this->config['display_name_attributes'];
222 foreach ($displayNameAttr as $dnAttr) {
223 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
224 if ($dnComponent !== null) {
225 $displayName[] = $dnComponent;
229 if (count($displayName) == 0) {
230 $displayName = $defaultValue;
232 $displayName = implode(' ', $displayName);
239 * Get the value to use as the external id saved in BookStack
240 * used to link the user to an existing BookStack DB user.
242 protected function getExternalId(array $samlAttributes, string $defaultValue)
244 $userNameAttr = $this->config['external_id_attribute'];
245 if ($userNameAttr === null) {
246 return $defaultValue;
249 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
253 * Extract the details of a user from a SAML response.
254 * @throws SamlException
256 public function getUserDetails(string $samlID, $samlAttributes): array
258 $emailAttr = $this->config['email_attribute'];
259 $externalId = $this->getExternalId($samlAttributes, $samlID);
260 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, null);
262 if ($email === null) {
263 throw new SamlException(trans('errors.saml_no_email_address'));
267 'external_id' => $externalId,
268 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
270 'saml_id' => $samlID,
275 * Get the groups a user is a part of from the SAML response.
277 public function getUserGroups(array $samlAttributes): array
279 $groupsAttr = $this->config['group_attribute'];
280 $userGroups = $samlAttributes[$groupsAttr] ?? null;
282 if (!is_array($userGroups)) {
290 * For an array of strings, return a default for an empty array,
291 * a string for an array with one element and the full array for
292 * more than one element.
294 protected function simplifyValue(array $data, $defaultValue)
296 switch (count($data)) {
298 $data = $defaultValue;
308 * Get a property from an SAML response.
309 * Handles properties potentially being an array.
311 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
313 if (isset($samlAttributes[$propertyKey])) {
314 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
317 return $defaultValue;
321 * Register a user that is authenticated but not already registered.
323 protected function registerUser(array $userDetails): User
325 // Create an array of the user data to create a new user instance
327 'name' => $userDetails['name'],
328 'email' => $userDetails['email'],
329 'password' => Str::random(32),
330 'external_auth_id' => $userDetails['external_id'],
331 'email_confirmed' => true,
334 $existingUser = $this->user->newQuery()->where('email', '=', $userDetails['email'])->first();
336 throw new SamlException(trans('errors.saml_email_exists', ['email' => $userDetails['email']]));
339 $user = $this->user->forceCreate($userData);
340 $this->userRepo->attachDefaultRole($user);
341 $this->userRepo->downloadAndAssignUserAvatar($user);
346 * Get the user from the database for the specified details.
348 protected function getOrRegisterUser(array $userDetails): ?User
350 $isRegisterEnabled = $this->config['auto_register'] === true;
352 ->where('external_auth_id', $userDetails['external_id'])
355 if ($user === null && $isRegisterEnabled) {
356 $user = $this->registerUser($userDetails);
363 * Process the SAML response for a user. Login the user when
364 * they exist, optionally registering them automatically.
365 * @throws SamlException
366 * @throws JsonDebugException
368 public function processLoginCallback(string $samlID, array $samlAttributes): User
370 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
371 $isLoggedIn = auth()->check();
373 if ($this->config['dump_user_details']) {
374 throw new JsonDebugException([
375 'attrs_from_idp' => $samlAttributes,
376 'attrs_after_parsing' => $userDetails,
381 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
384 $user = $this->getOrRegisterUser($userDetails);
385 if ($user === null) {
386 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
389 if ($this->shouldSyncGroups()) {
390 $groups = $this->getUserGroups($samlAttributes);
391 $this->syncWithGroups($user, $groups);
394 auth()->login($user);