]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Saml2Service.php
57db3ce65ec4dd5f77057d6efe289ad5b90d5b19
[bookstack] / app / Auth / Access / Saml2Service.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\User;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\SamlException;
6 use Illuminate\Support\Str;
7
8 /**
9  * Class Saml2Service
10  * Handles any app-specific SAML tasks.
11  */
12 class Saml2Service extends ExternalAuthService
13 {
14     protected $config;
15     protected $userRepo;
16     protected $user;
17     protected $enabled;
18
19     /**
20      * Saml2Service constructor.
21      */
22     public function __construct(UserRepo $userRepo, User $user)
23     {
24         $this->config = config('services.saml');
25         $this->userRepo = $userRepo;
26         $this->user = $user;
27         $this->enabled = config('saml2_settings.enabled') === true;
28     }
29
30     /**
31      * Check if groups should be synced.
32      */
33     protected function shouldSyncGroups(): bool
34     {
35         return $this->enabled && $this->config['user_to_groups'] !== false;
36     }
37
38     /**
39      * Calculate the display name
40      */
41     protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
42     {
43         $displayNameAttr = $this->config['display_name_attributes'];
44
45         $displayName = [];
46         foreach ($displayNameAttr as $dnAttr) {
47             $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
48             if ($dnComponent !== null) {
49                 $displayName[] = $dnComponent;
50             }
51         }
52
53         if (count($displayName) == 0) {
54             $displayName = $defaultValue;
55         } else {
56             $displayName = implode(' ', $displayName);
57         }
58
59         return $displayName;
60     }
61
62     /**
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.
65      */
66     protected function getExternalId(array $samlAttributes, string $defaultValue)
67     {
68         $userNameAttr = $this->config['external_id_attribute'];
69         if ($userNameAttr === null) {
70             return $defaultValue;
71         }
72
73         return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
74     }
75
76     /**
77      * Extract the details of a user from a SAML response.
78      * @throws SamlException
79      */
80     public function getUserDetails(string $samlID, $samlAttributes): array
81     {
82         $emailAttr = $this->config['email_attribute'];
83         $externalId = $this->getExternalId($samlAttributes, $samlID);
84         $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, null);
85
86         if ($email === null) {
87             throw new SamlException(trans('errors.saml_no_email_address'));
88         }
89
90         return [
91             'external_id' => $externalId,
92             'name' => $this->getUserDisplayName($samlAttributes, $externalId),
93             'email' => $email,
94             'saml_id' => $samlID,
95         ];
96     }
97
98     /**
99      * Get the groups a user is a part of from the SAML response.
100      */
101     public function getUserGroups(array $samlAttributes): array
102     {
103         $groupsAttr = $this->config['group_attribute'];
104         $userGroups = $samlAttributes[$groupsAttr] ?? null;
105
106         if (!is_array($userGroups)) {
107             $userGroups = [];
108         }
109
110         return $userGroups;
111     }
112
113     /**
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.
117      */
118     protected function simplifyValue(array $data, $defaultValue)
119     {
120         switch (count($data)) {
121             case 0:
122                 $data = $defaultValue;
123                 break;
124             case 1:
125                 $data = $data[0];
126                 break;
127         }
128         return $data;
129     }
130
131     /**
132      * Get a property from an SAML response.
133      * Handles properties potentially being an array.
134      */
135     protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
136     {
137         if (isset($samlAttributes[$propertyKey])) {
138             return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
139         }
140
141         return $defaultValue;
142     }
143
144     /**
145      *  Register a user that is authenticated but not already registered.
146      */
147     protected function registerUser(array $userDetails): User
148     {
149         // Create an array of the user data to create a new user instance
150         $userData = [
151             'name' => $userDetails['name'],
152             'email' => $userDetails['email'],
153             'password' => Str::random(32),
154             'external_auth_id' => $userDetails['external_id'],
155             'email_confirmed' => true,
156         ];
157
158         // TODO - Handle duplicate email address scenario
159         $user = $this->user->forceCreate($userData);
160         $this->userRepo->attachDefaultRole($user);
161         $this->userRepo->downloadAndAssignUserAvatar($user);
162         return $user;
163     }
164
165     /**
166      * Get the user from the database for the specified details.
167      */
168     protected function getOrRegisterUser(array $userDetails): ?User
169     {
170         $isRegisterEnabled = config('services.saml.auto_register') === true;
171         $user = $this->user
172           ->where('external_auth_id', $userDetails['external_id'])
173           ->first();
174
175         if ($user === null && $isRegisterEnabled) {
176             $user = $this->registerUser($userDetails);
177         }
178
179         return $user;
180     }
181
182     /**
183      * Process the SAML response for a user. Login the user when
184      * they exist, optionally registering them automatically.
185      * @throws SamlException
186      */
187     public function processLoginCallback(string $samlID, array $samlAttributes): User
188     {
189         $userDetails = $this->getUserDetails($samlID, $samlAttributes);
190         $isLoggedIn = auth()->check();
191
192         if ($isLoggedIn) {
193             throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
194         }
195
196         $user = $this->getOrRegisterUser($userDetails);
197         if ($user === null) {
198             throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
199         }
200
201         if ($this->shouldSyncGroups()) {
202             $groups = $this->getUserGroups($samlAttributes);
203             $this->syncWithGroups($user, $groups);
204         }
205
206         auth()->login($user);
207         return $user;
208     }
209 }