1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\Role;
4 use BookStack\Auth\User;
5 use Illuminate\Database\Eloquent\Builder;
6 use Illuminate\Support\Collection;
7 use Illuminate\Support\Facades\DB;
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)));
22 return in_array($roleName, $groupNames);
26 * Check if the given external auth ID string matches one of the given group names.
28 protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
30 $externalAuthIds = explode(',', strtolower($externalId));
32 foreach ($externalAuthIds as $externalAuthId) {
33 if (in_array(trim($externalAuthId), $groupNames)) {
42 * Match an array of group names to BookStack system roles.
43 * Formats group names to be lower-case and hyphenated.
45 protected function matchGroupsToSystemsRoles(array $groupNames): Collection
47 foreach ($groupNames as $i => $groupName) {
48 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
51 $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
52 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
53 return $this->roleMatchesGroupNames($role, $groupNames);
56 return $matchedRoles->pluck('id');
60 * Sync the groups to the user roles for the current user
62 public function syncWithGroups(User $user, array $userGroups): void
64 // Get the ids for the roles from the names
65 $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
68 if ($this->config['remove_from_groups']) {
69 $user->roles()->sync($groupsAsRoles);
70 $user->attachDefaultRole();
72 $user->roles()->syncWithoutDetaching($groupsAsRoles);