]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/ExternalAuthService.php
4c71db21adff7a559b929353ec4974512c16df14
[bookstack] / app / Auth / Access / ExternalAuthService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\Role;
4 use BookStack\Auth\User;
5 use Illuminate\Database\Eloquent\Builder;
6 use Illuminate\Support\Collection;
7 use Illuminate\Support\Facades\DB;
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         return in_array($roleName, $groupNames);
23     }
24
25     /**
26      * Check if the given external auth ID string matches one of the given group names.
27      */
28     protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
29     {
30         $externalAuthIds = explode(',', strtolower($externalId));
31
32         foreach ($externalAuthIds as $externalAuthId) {
33             if (in_array(trim($externalAuthId), $groupNames)) {
34                 return true;
35             }
36         }
37
38         return false;
39     }
40
41     /**
42      * Match an array of group names to BookStack system roles.
43      * Formats group names to be lower-case and hyphenated.
44      */
45     protected function matchGroupsToSystemsRoles(array $groupNames): Collection
46     {
47         foreach ($groupNames as $i => $groupName) {
48             $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
49         }
50
51         $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
52         $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
53             return $this->roleMatchesGroupNames($role, $groupNames);
54         });
55
56         return $matchedRoles->pluck('id');
57     }
58
59     /**
60      * Sync the groups to the user roles for the current user
61      */
62     public function syncWithGroups(User $user, array $userGroups): void
63     {
64         // Get the ids for the roles from the names
65         $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
66
67         // Sync groups
68         if ($this->config['remove_from_groups']) {
69             $user->roles()->sync($groupsAsRoles);
70             $user->attachDefaultRole();
71         } else {
72             $user->roles()->syncWithoutDetaching($groupsAsRoles);
73         }
74     }
75 }