]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Saml2Service.php
bb57ceb73a46221e11f8fb9358d9d8ffa1d77bad
[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
151         $userData = [
152             'name' => $userDetails['name'],
153             'email' => $userDetails['email'] ?? '',
154             'password' => Str::random(32),
155             'external_auth_id' => $userDetails['external_id'],
156             'email_confirmed' => true,
157         ];
158
159         // TODO - Handle duplicate email address scenario
160         $user = $this->user->forceCreate($userData);
161         $this->userRepo->attachDefaultRole($user);
162         $this->userRepo->downloadAndAssignUserAvatar($user);
163         return $user;
164     }
165
166     /**
167      * Get the user from the database for the specified details.
168      */
169     protected function getOrRegisterUser(array $userDetails): ?User
170     {
171         $isRegisterEnabled = config('services.saml.auto_register') === true;
172         $user = $this->user
173           ->where('external_auth_id', $userDetails['external_id'])
174           ->first();
175
176         if ($user === null && $isRegisterEnabled) {
177             $user = $this->registerUser($userDetails);
178         }
179
180         return $user;
181     }
182
183     /**
184      * Process the SAML response for a user. Login the user when
185      * they exist, optionally registering them automatically.
186      * @throws SamlException
187      */
188     public function processLoginCallback(string $samlID, array $samlAttributes): User
189     {
190         $userDetails = $this->getUserDetails($samlID, $samlAttributes);
191         $isLoggedIn = auth()->check();
192
193         if ($isLoggedIn) {
194             throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
195         }
196
197         $user = $this->getOrRegisterUser($userDetails);
198         if ($user === null) {
199             throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
200         }
201
202         if ($this->shouldSyncGroups()) {
203             $groups = $this->getUserGroups($samlAttributes);
204             $this->syncWithGroups($user, $groups);
205         }
206
207         auth()->login($user);
208         return $user;
209     }
210 }