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.
13 protected function roleMatchesGroupNames(Role $role, array $groupNames): bool
15 if ($role->external_auth_id) {
16 return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames);
19 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
20 return in_array($roleName, $groupNames);
24 * Check if the given external auth ID string matches one of the given group names.
26 protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
28 $externalAuthIds = explode(',', strtolower($externalId));
30 foreach ($externalAuthIds as $externalAuthId) {
31 if (in_array(trim($externalAuthId), $groupNames)) {
40 * Match an array of group names to BookStack system roles.
41 * Formats group names to be lower-case and hyphenated.
42 * @param array $groupNames
43 * @return \Illuminate\Support\Collection
45 protected function matchGroupsToSystemsRoles(array $groupNames)
47 foreach ($groupNames as $i => $groupName) {
48 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
51 $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
52 $query->whereIn('name', $groupNames);
53 foreach ($groupNames as $groupName) {
54 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
58 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
59 return $this->roleMatchesGroupNames($role, $groupNames);
62 return $matchedRoles->pluck('id');
66 * Sync the groups to the user roles for the current user
67 * @param \BookStack\Auth\User $user
68 * @param array $userGroups
70 public function syncWithGroups(User $user, array $userGroups)
72 // Get the ids for the roles from the names
73 $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
76 if ($this->config['remove_from_groups']) {
77 $user->roles()->sync($groupsAsRoles);
78 $this->userRepo->attachDefaultRole($user);
80 $user->roles()->syncWithoutDetaching($groupsAsRoles);