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