1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\Role;
4 use BookStack\Auth\User;
5 use Illuminate\Database\Eloquent\Builder;
7 class ExternalAuthService
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
16 protected function roleMatchesGroupNames(Role $role, array $groupNames)
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)) {
28 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
29 return in_array($roleName, $groupNames);
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
38 protected function matchGroupsToSystemsRoles(array $groupNames)
40 foreach ($groupNames as $i => $groupName) {
41 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
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 . '%');
51 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
52 return $this->roleMatchesGroupNames($role, $groupNames);
55 return $matchedRoles->pluck('id');
59 * Sync the groups to the user roles for the current user
60 * @param \BookStack\Auth\User $user
61 * @param array $userGroups
63 public function syncWithGroups(User $user, array $userGroups)
65 // Get the ids for the roles from the names
66 $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
69 if ($this->config['remove_from_groups']) {
70 $user->roles()->sync($groupsAsRoles);
71 $this->userRepo->attachDefaultRole($user);
73 $user->roles()->syncWithoutDetaching($groupsAsRoles);