- /**
- * Get all users as Builder for API.
- */
- public function getApiUsersBuilder(): Builder
- {
- return User::query()->select(['*'])
- ->scopes('withLastActivityAt')
- ->with(['avatar']);
- }
-
- /**
- * Get all the users with their permissions in a paginated format.
- * Note: Due to the use of email search this should only be used when
- * user is assumed to be trusted. (Admin users).
- * Email search can be abused to extract email addresses.
- */
- public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
- {
- $sort = $sortData['sort'];
-
- $query = User::query()->select(['*'])
- ->scopes(['withLastActivityAt'])
- ->with(['roles', 'avatar'])
- ->withCount('mfaValues')
- ->orderBy($sort, $sortData['order']);
-
- if ($sortData['search']) {
- $term = '%' . $sortData['search'] . '%';
- $query->where(function ($query) use ($term) {
- $query->where('name', 'like', $term)
- ->orWhere('email', 'like', $term);
- });
- }
-
- return $query->paginate($count);
- }
-
- /**
- * Assign a user to a system-level role.
- *
- * @throws NotFoundException
- */
- public function attachSystemRole(User $user, string $systemRoleName)
- {
- $role = Role::getSystemRole($systemRoleName);
- if (is_null($role)) {
- throw new NotFoundException("Role '{$systemRoleName}' not found");
- }
- $user->attachRole($role);
- }
-
- /**
- * Checks if the give user is the only admin.
- */
- public function isOnlyAdmin(User $user): bool
- {
- if (!$user->hasSystemRole('admin')) {
- return false;
- }
-
- $adminRole = Role::getSystemRole('admin');
- if ($adminRole->users()->count() > 1) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Set the assigned user roles via an array of role IDs.
- *
- * @throws UserUpdateException
- */
- public function setUserRoles(User $user, array $roles)
- {
- if ($this->demotingLastAdmin($user, $roles)) {
- throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
- }
-
- $user->roles()->sync($roles);
- }
-
- /**
- * Check if the given user is the last admin and their new roles no longer
- * contains the admin role.
- */
- protected function demotingLastAdmin(User $user, array $newRoles): bool
- {
- if ($this->isOnlyAdmin($user)) {
- $adminRole = Role::getSystemRole('admin');
- if (!in_array(strval($adminRole->id), $newRoles)) {
- return true;
- }
- }
-
- return false;
- }
-