3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use Illuminate\Support\Collection;
9 class ExternalAuthService
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.
15 protected function roleMatchesGroupNames(Role $role, array $groupNames): bool
17 if ($role->external_auth_id) {
18 return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames);
21 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
23 return in_array($roleName, $groupNames);
27 * Check if the given external auth ID string matches one of the given group names.
29 protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
31 $externalAuthIds = explode(',', strtolower($externalId));
33 foreach ($externalAuthIds as $externalAuthId) {
34 if (in_array(trim($externalAuthId), $groupNames)) {
43 * Match an array of group names to BookStack system roles.
44 * Formats group names to be lower-case and hyphenated.
46 protected function matchGroupsToSystemsRoles(array $groupNames): Collection
48 foreach ($groupNames as $i => $groupName) {
49 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
52 $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
53 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
54 return $this->roleMatchesGroupNames($role, $groupNames);
57 return $matchedRoles->pluck('id');
61 * Sync the groups to the user roles for the current user.
63 public function syncWithGroups(User $user, array $userGroups): void
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 $user->attachDefaultRole();
73 $user->roles()->syncWithoutDetaching($groupsAsRoles);