1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\Role;
4 use BookStack\Auth\User;
6 class ExternalAuthService
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
15 protected function roleMatchesGroupNames(Role $role, array $groupNames)
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)) {
27 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
28 return in_array($roleName, $groupNames);
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
37 protected function matchGroupsToSystemsRoles(array $groupNames)
39 foreach ($groupNames as $i => $groupName) {
40 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
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 . '%');
50 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
51 return $this->roleMatchesGroupNames($role, $groupNames);
54 return $matchedRoles->pluck('id');
58 * Sync the groups to the user roles for the current user
59 * @param \BookStack\Auth\User $user
60 * @param array $samlAttributes
62 public function syncWithGroups(User $user, array $userGroups)
64 // Get the ids for the roles from the names
65 $samlGroupsAsRoles = $this->matchGroupsToSystemsRoles($userSamlGroups);
68 if ($this->config['remove_from_groups']) {
69 $user->roles()->sync($samlGroupsAsRoles);
70 $this->userRepo->attachDefaultRole($user);
72 $user->roles()->syncWithoutDetaching($samlGroupsAsRoles);