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