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.
162 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
164 public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
167 $user->name = $data['name'];
168 $user->email = $data['email'];
169 $user->password = bcrypt(empty($data['password']) ? Str::random(32) : $data['password']);
170 $user->email_confirmed = $emailConfirmed;
171 $user->external_auth_id = $data['external_auth_id'] ?? '';
173 $user->refreshSlug();
176 if (!empty($data['language'])) {
177 setting()->putUser($user, 'language', $data['language']);
180 if (isset($data['roles'])) {
181 $this->setUserRoles($user, $data['roles']);
184 $this->downloadAndAssignUserAvatar($user);
190 * As per "createWithoutActivity" but records a "create" activity.
191 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
193 public function create(array $data, bool $sendInvite = false): User
195 $user = $this->createWithoutActivity($data, true);
198 $this->inviteService->sendInvitation($user);
201 Activity::add(ActivityType::USER_CREATE, $user);
206 * Update the given user with the given data.
207 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
208 * @throws UserUpdateException
210 public function update(User $user, array $data, bool $manageUsersAllowed): User
212 if (!empty($data['name'])) {
213 $user->name = $data['name'];
214 $user->refreshSlug();
217 if (!empty($data['email']) && $manageUsersAllowed) {
218 $user->email = $data['email'];
221 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
222 $user->external_auth_id = $data['external_auth_id'];
225 if (isset($data['roles']) && $manageUsersAllowed) {
226 $this->setUserRoles($user, $data['roles']);
229 if (!empty($data['password'])) {
230 $user->password = bcrypt($data['password']);
233 if (!empty($data['language'])) {
234 setting()->putUser($user, 'language', $data['language']);
238 Activity::add(ActivityType::USER_UPDATE, $user);
244 * Remove the given user from storage, Delete all related content.
248 public function destroy(User $user, ?int $newOwnerId = null)
250 $this->ensureDeletable($user);
252 $user->socialAccounts()->delete();
253 $user->apiTokens()->delete();
254 $user->favourites()->delete();
255 $user->mfaValues()->delete();
258 // Delete user profile images
259 $this->userAvatar->destroyAllForUser($user);
261 if (!empty($newOwnerId)) {
262 $newOwner = User::query()->find($newOwnerId);
263 if (!is_null($newOwner)) {
264 $this->migrateOwnership($user, $newOwner);
268 Activity::add(ActivityType::USER_DELETE, $user);
272 * @throws NotifyException
274 protected function ensureDeletable(User $user): void
276 if ($this->isOnlyAdmin($user)) {
277 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
280 if ($user->system_name === 'public') {
281 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
286 * Migrate ownership of items in the system from one user to another.
288 protected function migrateOwnership(User $fromUser, User $toUser)
290 $entities = (new EntityProvider())->all();
291 foreach ($entities as $instance) {
292 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
293 ->update(['owned_by' => $toUser->id]);
298 * Get the recently created content for this given user.
300 public function getRecentlyCreated(User $user, int $count = 20): array
302 $query = function (Builder $query) use ($user, $count) {
303 return $query->orderBy('created_at', 'desc')
304 ->where('created_by', '=', $user->id)
310 'pages' => $query(Page::visible()->where('draft', '=', false)),
311 'chapters' => $query(Chapter::visible()),
312 'books' => $query(Book::visible()),
313 'shelves' => $query(Bookshelf::visible()),
318 * Get asset created counts for the give user.
320 public function getAssetCounts(User $user): array
322 $createdBy = ['created_by' => $user->id];
325 'pages' => Page::visible()->where($createdBy)->count(),
326 'chapters' => Chapter::visible()->where($createdBy)->count(),
327 'books' => Book::visible()->where($createdBy)->count(),
328 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
333 * Get the roles in the system that are assignable to a user.
335 public function getAllRoles(): Collection
337 return Role::query()->orderBy('display_name', 'asc')->get();
341 * Get an avatar image for a user and set it as their avatar.
342 * Returns early if avatars disabled or not set in config.
344 public function downloadAndAssignUserAvatar(User $user): void
347 $this->userAvatar->fetchAndAssignToUser($user);
348 } catch (Exception $e) {
349 Log::error('Failed to save user avatar image');