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\Str;
8 class ExternalAuthService
10 protected $registrationService;
14 * ExternalAuthService base constructor.
16 public function __construct(RegistrationService $registrationService, User $user)
18 $this->registrationService = $registrationService;
23 * Get the user from the database for the specified details.
24 * @throws UserRegistrationException
26 protected function getOrRegisterUser(array $userDetails): ?User
28 $user = $this->user->newQuery()
29 ->where('external_auth_id', '=', $userDetails['external_id'])
34 'name' => $userDetails['name'],
35 'email' => $userDetails['email'],
36 'password' => Str::random(32),
37 'external_auth_id' => $userDetails['external_id'],
40 $user = $this->registrationService->registerUser($userData, null, false);
47 * Check a role against an array of group names to see if it matches.
48 * Checked against role 'external_auth_id' if set otherwise the name of the role.
50 protected function roleMatchesGroupNames(Role $role, array $groupNames): bool
52 if ($role->external_auth_id) {
53 return $this->externalIdMatchesGroupNames($role->external_auth_id, $groupNames);
56 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
57 return in_array($roleName, $groupNames);
61 * Check if the given external auth ID string matches one of the given group names.
63 protected function externalIdMatchesGroupNames(string $externalId, array $groupNames): bool
65 $externalAuthIds = explode(',', strtolower($externalId));
67 foreach ($externalAuthIds as $externalAuthId) {
68 if (in_array(trim($externalAuthId), $groupNames)) {
77 * Match an array of group names to BookStack system roles.
78 * Formats group names to be lower-case and hyphenated.
79 * @param array $groupNames
80 * @return \Illuminate\Support\Collection
82 protected function matchGroupsToSystemsRoles(array $groupNames)
84 foreach ($groupNames as $i => $groupName) {
85 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
88 $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
89 $query->whereIn('name', $groupNames);
90 foreach ($groupNames as $groupName) {
91 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
95 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
96 return $this->roleMatchesGroupNames($role, $groupNames);
99 return $matchedRoles->pluck('id');
103 * Sync the groups to the user roles for the current user
105 public function syncWithGroups(User $user, array $userGroups): void
107 // Get the ids for the roles from the names
108 $groupsAsRoles = $this->matchGroupsToSystemsRoles($userGroups);
111 if ($this->config['remove_from_groups']) {
112 $user->roles()->sync($groupsAsRoles);
113 $user->attachDefaultRole();
115 $user->roles()->syncWithoutDetaching($groupsAsRoles);