]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/ExternalAuthService.php
Reviewed and refactored additional editor draft save warnings
[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 Illuminate\Support\Collection;
8
9 class ExternalAuthService
10 {
11     /**
12      * Check a role against an array of group names to see if it matches.
13      * Checked against role 'external_auth_id' if set otherwise the name of the role.
14      */
15     protected function roleMatchesGroupNames(Role $role, array $groupNames): bool
16     {
17         if ($role->external_auth_id) {
18             return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames);
19         }
20
21         $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
22
23         return in_array($roleName, $groupNames);
24     }
25
26     /**
27      * Check if the given external auth ID string matches one of the given group names.
28      */
29     protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
30     {
31         $externalAuthIds = explode(',', strtolower($externalId));
32
33         foreach ($externalAuthIds as $externalAuthId) {
34             if (in_array(trim($externalAuthId), $groupNames)) {
35                 return true;
36             }
37         }
38
39         return false;
40     }
41
42     /**
43      * Match an array of group names to BookStack system roles.
44      * Formats group names to be lower-case and hyphenated.
45      */
46     protected function matchGroupsToSystemsRoles(array $groupNames): Collection
47     {
48         foreach ($groupNames as $i => $groupName) {
49             $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
50         }
51
52         $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
53         $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
54             return $this->roleMatchesGroupNames($role, $groupNames);
55         });
56
57         return $matchedRoles->pluck('id');
58     }
59
60     /**
61      * Sync the groups to the user roles for the current user.
62      */
63     public function syncWithGroups(User $user, array $userGroups): void
64     {
65         // Get the ids for the roles from the names
66         $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
67
68         // Sync groups
69         if ($this->config['remove_from_groups']) {
70             $user->roles()->sync($groupsAsRoles);
71             $user->attachDefaultRole();
72         } else {
73             $user->roles()->syncWithoutDetaching($groupsAsRoles);
74         }
75     }
76 }