1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\SamlException;
6 use Illuminate\Support\Str;
10 * Handles any app-specific SAML tasks.
12 class Saml2Service extends ExternalAuthService
20 * Saml2Service constructor.
22 public function __construct(UserRepo $userRepo, User $user)
24 $this->config = config('services.saml');
25 $this->userRepo = $userRepo;
27 $this->enabled = config('saml2_settings.enabled') === true;
31 * Check if groups should be synced.
33 protected function shouldSyncGroups(): bool
35 return $this->enabled && $this->config['user_to_groups'] !== false;
39 * Calculate the display name
41 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
43 $displayNameAttr = $this->config['display_name_attributes'];
46 foreach ($displayNameAttr as $dnAttr) {
47 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
48 if ($dnComponent !== null) {
49 $displayName[] = $dnComponent;
53 if (count($displayName) == 0) {
54 $displayName = $defaultValue;
56 $displayName = implode(' ', $displayName);
63 * Get the value to use as the external id saved in BookStack
64 * used to link the user to an existing BookStack DB user.
66 protected function getExternalId(array $samlAttributes, string $defaultValue)
68 $userNameAttr = $this->config['external_id_attribute'];
69 if ($userNameAttr === null) {
73 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
77 * Extract the details of a user from a SAML response.
78 * @throws SamlException
80 public function getUserDetails(string $samlID, $samlAttributes): array
82 $emailAttr = $this->config['email_attribute'];
83 $externalId = $this->getExternalId($samlAttributes, $samlID);
84 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, null);
86 if ($email === null) {
87 throw new SamlException(trans('errors.saml_no_email_address'));
91 'external_id' => $externalId,
92 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
99 * Get the groups a user is a part of from the SAML response.
101 public function getUserGroups(array $samlAttributes): array
103 $groupsAttr = $this->config['group_attribute'];
104 $userGroups = $samlAttributes[$groupsAttr] ?? null;
106 if (!is_array($userGroups)) {
114 * For an array of strings, return a default for an empty array,
115 * a string for an array with one element and the full array for
116 * more than one element.
118 protected function simplifyValue(array $data, $defaultValue)
120 switch (count($data)) {
122 $data = $defaultValue;
132 * Get a property from an SAML response.
133 * Handles properties potentially being an array.
135 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
137 if (isset($samlAttributes[$propertyKey])) {
138 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
141 return $defaultValue;
145 * Register a user that is authenticated but not already registered.
147 protected function registerUser(array $userDetails): User
149 // Create an array of the user data to create a new user instance
151 'name' => $userDetails['name'],
152 'email' => $userDetails['email'],
153 'password' => Str::random(32),
154 'external_auth_id' => $userDetails['external_id'],
155 'email_confirmed' => true,
158 // TODO - Handle duplicate email address scenario
159 $user = $this->user->forceCreate($userData);
160 $this->userRepo->attachDefaultRole($user);
161 $this->userRepo->downloadAndAssignUserAvatar($user);
166 * Get the user from the database for the specified details.
168 protected function getOrRegisterUser(array $userDetails): ?User
170 $isRegisterEnabled = config('services.saml.auto_register') === true;
172 ->where('external_auth_id', $userDetails['external_id'])
175 if ($user === null && $isRegisterEnabled) {
176 $user = $this->registerUser($userDetails);
183 * Process the SAML response for a user. Login the user when
184 * they exist, optionally registering them automatically.
185 * @throws SamlException
187 public function processLoginCallback(string $samlID, array $samlAttributes): User
189 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
190 $isLoggedIn = auth()->check();
193 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
196 $user = $this->getOrRegisterUser($userDetails);
197 if ($user === null) {
198 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
201 if ($this->shouldSyncGroups()) {
202 $groups = $this->getUserGroups($samlAttributes);
203 $this->syncWithGroups($user, $groups);
206 auth()->login($user);