3 namespace BookStack\Access;
5 use BookStack\Users\Models\Role;
6 use BookStack\Users\Models\User;
7 use Illuminate\Support\Collection;
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 foreach ($this->parseRoleExternalAuthId($externalId) as $externalAuthId) {
32 if (in_array($externalAuthId, $groupNames)) {
40 protected function parseRoleExternalAuthId(string $externalId): array
42 $inputIds = preg_split('/(?<!\\\),/', strtolower($externalId));
45 foreach ($inputIds as $inputId) {
46 $cleanIds[] = str_replace('\,', ',', trim($inputId));
53 * Match an array of group names to BookStack system roles.
54 * Formats group names to be lower-case and hyphenated.
56 protected function matchGroupsToSystemsRoles(array $groupNames): Collection
58 foreach ($groupNames as $i => $groupName) {
59 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
62 $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
63 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
64 return $this->roleMatchesGroupNames($role, $groupNames);
67 return $matchedRoles->pluck('id');
71 * Sync the groups to the user roles for the current user.
73 public function syncUserWithFoundGroups(User $user, array $userGroups, bool $detachExisting): void
75 // Get the ids for the roles from the names
76 $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
79 if ($detachExisting) {
80 $user->roles()->sync($groupsAsRoles);
81 $user->attachDefaultRole();
83 $user->roles()->syncWithoutDetaching($groupsAsRoles);