3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use Illuminate\Support\Collection;
8 use Illuminate\Database\Eloquent\Builder;
9 use Illuminate\Support\Str;
11 class ExternalAuthService
13 protected $registrationService;
17 * ExternalAuthService base constructor.
19 public function __construct(RegistrationService $registrationService, User $user)
21 $this->registrationService = $registrationService;
26 * Get the user from the database for the specified details.
27 * @throws UserRegistrationException
29 protected function getOrRegisterUser(array $userDetails): ?User
32 ->where('external_auth_id', '=', $userDetails['external_id'])
37 'name' => $userDetails['name'],
38 'email' => $userDetails['email'],
39 'password' => Str::random(32),
40 'external_auth_id' => $userDetails['external_id'],
43 $user = $this->registrationService->registerUser($userData, null, false);
50 * Check a role against an array of group names to see if it matches.
51 * Checked against role 'external_auth_id' if set otherwise the name of the role.
53 protected function roleMatchesGroupNames(Role $role, array $groupNames): bool
55 if ($role->external_auth_id) {
56 return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames);
59 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
61 return in_array($roleName, $groupNames);
65 * Check if the given external auth ID string matches one of the given group names.
67 protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
69 $externalAuthIds = explode(',', strtolower($externalId));
71 foreach ($externalAuthIds as $externalAuthId) {
72 if (in_array(trim($externalAuthId), $groupNames)) {
81 * Match an array of group names to BookStack system roles.
82 * Formats group names to be lower-case and hyphenated.
84 protected function matchGroupsToSystemsRoles(array $groupNames): Collection
86 foreach ($groupNames as $i => $groupName) {
87 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
90 $roles = Role::query()->get(['id', 'external_auth_id', 'display_name']);
91 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
92 return $this->roleMatchesGroupNames($role, $groupNames);
95 return $matchedRoles->pluck('id');
99 * Sync the groups to the user roles for the current user.
101 public function syncWithGroups(User $user, array $userGroups): void
103 // Get the ids for the roles from the names
104 $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
107 if ($this->config['remove_from_groups']) {
108 $user->roles()->sync($groupsAsRoles);
109 $user->attachDefaultRole();
111 $user->roles()->syncWithoutDetaching($groupsAsRoles);