3 namespace BookStack\Auth;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\UserInviteService;
7 use BookStack\Entities\EntityProvider;
8 use BookStack\Entities\Models\Book;
9 use BookStack\Entities\Models\Bookshelf;
10 use BookStack\Entities\Models\Chapter;
11 use BookStack\Entities\Models\Page;
12 use BookStack\Exceptions\NotFoundException;
13 use BookStack\Exceptions\NotifyException;
14 use BookStack\Exceptions\UserUpdateException;
15 use BookStack\Facades\Activity;
16 use BookStack\Uploads\UserAvatars;
18 use Illuminate\Database\Eloquent\Builder;
19 use Illuminate\Database\Eloquent\Collection;
20 use Illuminate\Pagination\LengthAwarePaginator;
21 use Illuminate\Support\Facades\Log;
22 use Illuminate\Support\Str;
26 protected $userAvatar;
27 protected $inviteService;
30 * UserRepo constructor.
32 public function __construct(UserAvatars $userAvatar, UserInviteService $inviteService)
34 $this->userAvatar = $userAvatar;
35 $this->inviteService = $inviteService;
39 * Get a user by their email address.
41 public function getByEmail(string $email): ?User
43 return User::query()->where('email', '=', $email)->first();
47 * Get a user by their ID.
49 public function getById(int $id): User
51 return User::query()->findOrFail($id);
55 * Get a user by their slug.
57 public function getBySlug(string $slug): User
59 return User::query()->where('slug', '=', $slug)->firstOrFail();
63 * Get all users as Builder for API.
65 public function getApiUsersBuilder(): Builder
67 return User::query()->select(['*'])
68 ->scopes('withLastActivityAt')
73 * Get all the users with their permissions in a paginated format.
74 * Note: Due to the use of email search this should only be used when
75 * user is assumed to be trusted. (Admin users).
76 * Email search can be abused to extract email addresses.
78 public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
80 $sort = $sortData['sort'];
82 $query = User::query()->select(['*'])
83 ->scopes(['withLastActivityAt'])
84 ->with(['roles', 'avatar'])
85 ->withCount('mfaValues')
86 ->orderBy($sort, $sortData['order']);
88 if ($sortData['search']) {
89 $term = '%' . $sortData['search'] . '%';
90 $query->where(function ($query) use ($term) {
91 $query->where('name', 'like', $term)
92 ->orWhere('email', 'like', $term);
96 return $query->paginate($count);
100 * Assign a user to a system-level role.
102 * @throws NotFoundException
104 public function attachSystemRole(User $user, string $systemRoleName)
106 $role = Role::getSystemRole($systemRoleName);
107 if (is_null($role)) {
108 throw new NotFoundException("Role '{$systemRoleName}' not found");
110 $user->attachRole($role);
114 * Checks if the give user is the only admin.
116 public function isOnlyAdmin(User $user): bool
118 if (!$user->hasSystemRole('admin')) {
122 $adminRole = Role::getSystemRole('admin');
123 if ($adminRole->users()->count() > 1) {
131 * Set the assigned user roles via an array of role IDs.
133 * @throws UserUpdateException
135 public function setUserRoles(User $user, array $roles)
137 if ($this->demotingLastAdmin($user, $roles)) {
138 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
141 $user->roles()->sync($roles);
145 * Check if the given user is the last admin and their new roles no longer
146 * contains the admin role.
148 protected function demotingLastAdmin(User $user, array $newRoles): bool
150 if ($this->isOnlyAdmin($user)) {
151 $adminRole = Role::getSystemRole('admin');
152 if (!in_array(strval($adminRole->id), $newRoles)) {
161 * Create a new basic instance of user with the given pre-validated data.
163 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
165 public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
168 $user->name = $data['name'];
169 $user->email = $data['email'];
170 $user->password = bcrypt(empty($data['password']) ? Str::random(32) : $data['password']);
171 $user->email_confirmed = $emailConfirmed;
172 $user->external_auth_id = $data['external_auth_id'] ?? '';
174 $user->refreshSlug();
177 if (!empty($data['language'])) {
178 setting()->putUser($user, 'language', $data['language']);
181 if (isset($data['roles'])) {
182 $this->setUserRoles($user, $data['roles']);
185 $this->downloadAndAssignUserAvatar($user);
191 * As per "createWithoutActivity" but records a "create" activity.
193 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
195 public function create(array $data, bool $sendInvite = false): User
197 $user = $this->createWithoutActivity($data, true);
200 $this->inviteService->sendInvitation($user);
203 Activity::add(ActivityType::USER_CREATE, $user);
209 * Update the given user with the given data.
211 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
213 * @throws UserUpdateException
215 public function update(User $user, array $data, bool $manageUsersAllowed): User
217 if (!empty($data['name'])) {
218 $user->name = $data['name'];
219 $user->refreshSlug();
222 if (!empty($data['email']) && $manageUsersAllowed) {
223 $user->email = $data['email'];
226 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
227 $user->external_auth_id = $data['external_auth_id'];
230 if (isset($data['roles']) && $manageUsersAllowed) {
231 $this->setUserRoles($user, $data['roles']);
234 if (!empty($data['password'])) {
235 $user->password = bcrypt($data['password']);
238 if (!empty($data['language'])) {
239 setting()->putUser($user, 'language', $data['language']);
243 Activity::add(ActivityType::USER_UPDATE, $user);
249 * Remove the given user from storage, Delete all related content.
253 public function destroy(User $user, ?int $newOwnerId = null)
255 $this->ensureDeletable($user);
257 $user->socialAccounts()->delete();
258 $user->apiTokens()->delete();
259 $user->favourites()->delete();
260 $user->mfaValues()->delete();
263 // Delete user profile images
264 $this->userAvatar->destroyAllForUser($user);
266 if (!empty($newOwnerId)) {
267 $newOwner = User::query()->find($newOwnerId);
268 if (!is_null($newOwner)) {
269 $this->migrateOwnership($user, $newOwner);
273 Activity::add(ActivityType::USER_DELETE, $user);
277 * @throws NotifyException
279 protected function ensureDeletable(User $user): void
281 if ($this->isOnlyAdmin($user)) {
282 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
285 if ($user->system_name === 'public') {
286 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
291 * Migrate ownership of items in the system from one user to another.
293 protected function migrateOwnership(User $fromUser, User $toUser)
295 $entities = (new EntityProvider())->all();
296 foreach ($entities as $instance) {
297 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
298 ->update(['owned_by' => $toUser->id]);
303 * Get the recently created content for this given user.
305 public function getRecentlyCreated(User $user, int $count = 20): array
307 $query = function (Builder $query) use ($user, $count) {
308 return $query->orderBy('created_at', 'desc')
309 ->where('created_by', '=', $user->id)
315 'pages' => $query(Page::visible()->where('draft', '=', false)),
316 'chapters' => $query(Chapter::visible()),
317 'books' => $query(Book::visible()),
318 'shelves' => $query(Bookshelf::visible()),
323 * Get asset created counts for the give user.
325 public function getAssetCounts(User $user): array
327 $createdBy = ['created_by' => $user->id];
330 'pages' => Page::visible()->where($createdBy)->count(),
331 'chapters' => Chapter::visible()->where($createdBy)->count(),
332 'books' => Book::visible()->where($createdBy)->count(),
333 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
338 * Get the roles in the system that are assignable to a user.
340 public function getAllRoles(): Collection
342 return Role::query()->orderBy('display_name', 'asc')->get();
346 * Get an avatar image for a user and set it as their avatar.
347 * Returns early if avatars disabled or not set in config.
349 public function downloadAndAssignUserAvatar(User $user): void
352 $this->userAvatar->fetchAndAssignToUser($user);
353 } catch (Exception $e) {
354 Log::error('Failed to save user avatar image');