3 namespace BookStack\Users;
5 use BookStack\Access\UserInviteException;
6 use BookStack\Access\UserInviteService;
7 use BookStack\Activity\ActivityType;
8 use BookStack\Exceptions\NotifyException;
9 use BookStack\Exceptions\UserUpdateException;
10 use BookStack\Facades\Activity;
11 use BookStack\Uploads\UserAvatars;
12 use BookStack\Users\Models\Role;
13 use BookStack\Users\Models\User;
16 use Illuminate\Support\Facades\Hash;
17 use Illuminate\Support\Facades\Log;
18 use Illuminate\Support\Str;
22 public function __construct(
23 protected UserAvatars $userAvatar,
24 protected UserInviteService $inviteService
29 * Get a user by their email address.
31 public function getByEmail(string $email): ?User
33 return User::query()->where('email', '=', $email)->first();
37 * Get a user by their ID.
39 public function getById(int $id): User
41 return User::query()->findOrFail($id);
45 * Get a user by their slug.
47 public function getBySlug(string $slug): User
49 return User::query()->where('slug', '=', $slug)->firstOrFail();
53 * Create a new basic instance of user with the given pre-validated data.
55 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
57 public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
60 $user->name = $data['name'];
61 $user->email = $data['email'];
62 $user->password = Hash::make(empty($data['password']) ? Str::random(32) : $data['password']);
63 $user->email_confirmed = $emailConfirmed;
64 $user->external_auth_id = $data['external_auth_id'] ?? '';
69 if (!empty($data['language'])) {
70 setting()->putUser($user, 'language', $data['language']);
73 if (isset($data['roles'])) {
74 $this->setUserRoles($user, $data['roles']);
77 $this->downloadAndAssignUserAvatar($user);
83 * As per "createWithoutActivity" but records a "create" activity.
85 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
86 * @throws UserInviteException
88 public function create(array $data, bool $sendInvite = false): User
90 $user = $this->createWithoutActivity($data, true);
93 $this->inviteService->sendInvitation($user);
96 Activity::add(ActivityType::USER_CREATE, $user);
102 * Update the given user with the given data, but do not create an activity.
104 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
106 * @throws UserUpdateException
108 public function updateWithoutActivity(User $user, array $data, bool $manageUsersAllowed): User
110 if (!empty($data['name'])) {
111 $user->name = $data['name'];
112 $user->refreshSlug();
115 if (!empty($data['email']) && $manageUsersAllowed) {
116 $user->email = $data['email'];
119 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
120 $user->external_auth_id = $data['external_auth_id'];
123 if (isset($data['roles']) && $manageUsersAllowed) {
124 $this->setUserRoles($user, $data['roles']);
127 if (!empty($data['password'])) {
128 $user->password = Hash::make($data['password']);
131 if (!empty($data['language'])) {
132 setting()->putUser($user, 'language', $data['language']);
141 * Update the given user with the given data.
143 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
145 * @throws UserUpdateException
147 public function update(User $user, array $data, bool $manageUsersAllowed): User
149 $user = $this->updateWithoutActivity($user, $data, $manageUsersAllowed);
151 Activity::add(ActivityType::USER_UPDATE, $user);
157 * Remove the given user from storage, Delete all related content.
161 public function destroy(User $user, ?int $newOwnerId = null): void
163 $this->ensureDeletable($user);
165 $this->removeUserDependantRelations($user);
166 $this->nullifyUserNonDependantRelations($user);
169 // Delete user profile images
170 $this->userAvatar->destroyAllForUser($user);
172 // Delete related activities
173 setting()->deleteUserSettings($user->id);
175 // Migrate or nullify ownership
177 if (!empty($newOwnerId)) {
178 $newOwner = User::query()->find($newOwnerId);
180 $this->migrateOwnership($user, $newOwner);
182 Activity::add(ActivityType::USER_DELETE, $user);
185 protected function removeUserDependantRelations(User $user): void
187 $user->apiTokens()->delete();
188 $user->socialAccounts()->delete();
189 $user->favourites()->delete();
190 $user->mfaValues()->delete();
191 $user->watches()->delete();
193 $tables = ['email_confirmations', 'user_invites', 'views'];
194 foreach ($tables as $table) {
195 DB::table($table)->where('user_id', '=', $user->id)->delete();
198 protected function nullifyUserNonDependantRelations(User $user): void
201 'attachments' => ['created_by', 'updated_by'],
202 'comments' => ['created_by', 'updated_by'],
203 'deletions' => ['deleted_by'],
204 'entities' => ['created_by', 'updated_by'],
205 'images' => ['created_by', 'updated_by'],
206 'imports' => ['created_by'],
207 'joint_permissions' => ['owner_id'],
208 'page_revisions' => ['created_by'],
209 'sessions' => ['user_id'],
212 foreach ($toNullify as $table => $columns) {
213 foreach ($columns as $column) {
215 ->where($column, '=', $user->id)
216 ->update([$column => null]);
222 * @throws NotifyException
224 protected function ensureDeletable(User $user): void
226 if ($this->isOnlyAdmin($user)) {
227 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
230 if ($user->system_name === 'public') {
231 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
236 * Migrate ownership of items in the system from one user to another.
238 protected function migrateOwnership(User $fromUser, User|null $toUser): void
240 $newOwnerValue = $toUser ? $toUser->id : null;
241 DB::table('entities')
242 ->where('owned_by', '=', $fromUser->id)
243 ->update(['owned_by' => $newOwnerValue]);
247 * Get an avatar image for a user and set it as their avatar.
248 * Returns early if avatars disabled or not set in config.
250 protected function downloadAndAssignUserAvatar(User $user): void
253 $this->userAvatar->fetchAndAssignToUser($user);
254 } catch (Exception $e) {
255 Log::error('Failed to save user avatar image');
260 * Checks if the give user is the only admin.
262 protected function isOnlyAdmin(User $user): bool
264 if (!$user->hasSystemRole('admin')) {
268 $adminRole = Role::getSystemRole('admin');
269 if ($adminRole->users()->count() > 1) {
277 * Set the assigned user roles via an array of role IDs.
279 * @throws UserUpdateException
281 protected function setUserRoles(User $user, array $roles): void
283 $roles = array_filter(array_values($roles));
285 if ($this->demotingLastAdmin($user, $roles)) {
286 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
289 $user->roles()->sync($roles);
293 * Check if the given user is the last admin and their new roles no longer
294 * contain the admin role.
296 protected function demotingLastAdmin(User $user, array $newRoles): bool
298 if ($this->isOnlyAdmin($user)) {
299 $adminRole = Role::getSystemRole('admin');
300 if (!in_array(strval($adminRole->id), $newRoles)) {