]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/ExternalAuthService.php
Started refactor for merge of OIDC
[bookstack] / app / Auth / Access / ExternalAuthService.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\UserRegistrationException;
8 use Illuminate\Support\Collection;
9 use Illuminate\Support\Str;
10
11 class ExternalAuthService
12 {
13     protected $registrationService;
14     protected $user;
15
16     /**
17      * ExternalAuthService base constructor.
18      */
19     public function __construct(RegistrationService $registrationService, User $user)
20     {
21         $this->registrationService = $registrationService;
22         $this->user = $user;
23     }
24     
25     /**
26      * Get the user from the database for the specified details.
27      * @throws UserRegistrationException
28      */
29     protected function getOrRegisterUser(array $userDetails): ?User
30     {
31         $user = User::query()
32           ->where('external_auth_id', '=', $userDetails['external_id'])
33           ->first();
34
35         if (is_null($user)) {
36             $userData = [
37                 'name'             => $userDetails['name'],
38                 'email'            => $userDetails['email'],
39                 'password'         => Str::random(32),
40                 'external_auth_id' => $userDetails['external_id'],
41             ];
42
43             $user = $this->registrationService->registerUser($userData, null, false);
44         }
45
46         return $user;
47     }
48
49     /**
50      * Check a role against an array of group names to see if it matches.
51      * Checked against role 'external_auth_id' if set otherwise the name of the role.
52      */
53     protected function roleMatchesGroupNames(Role $role, array $groupNames): bool
54     {
55         if ($role->external_auth_id) {
56             return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames);
57         }
58
59         $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
60
61         return in_array($roleName, $groupNames);
62     }
63
64     /**
65      * Check if the given external auth ID string matches one of the given group names.
66      */
67     protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
68     {
69         $externalAuthIds = explode(',', strtolower($externalId));
70
71         foreach ($externalAuthIds as $externalAuthId) {
72             if (in_array(trim($externalAuthId), $groupNames)) {
73                 return true;
74             }
75         }
76
77         return false;
78     }
79
80     /**
81      * Match an array of group names to BookStack system roles.
82      * Formats group names to be lower-case and hyphenated.
83      */
84     protected function matchGroupsToSystemsRoles(array $groupNames): Collection
85     {
86         foreach ($groupNames as $i => $groupName) {
87             $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
88         }
89
90         $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
91         $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
92             return $this->roleMatchesGroupNames($role, $groupNames);
93         });
94
95         return $matchedRoles->pluck('id');
96     }
97
98     /**
99      * Sync the groups to the user roles for the current user.
100      */
101     public function syncWithGroups(User $user, array $userGroups): void
102     {
103         // Get the ids for the roles from the names
104         $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
105
106         // Sync groups
107         if ($this->config['remove_from_groups']) {
108             $user->roles()->sync($groupsAsRoles);
109             $user->attachDefaultRole();
110         } else {
111             $user->roles()->syncWithoutDetaching($groupsAsRoles);
112         }
113     }
114 }