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