3 namespace BookStack\Users;
5 use BookStack\Access\UserInviteException;
6 use BookStack\Access\UserInviteService;
7 use BookStack\Activity\ActivityType;
8 use BookStack\Entities\Tools\SlugGenerator;
9 use BookStack\Exceptions\NotifyException;
10 use BookStack\Exceptions\UserUpdateException;
11 use BookStack\Facades\Activity;
12 use BookStack\Uploads\UserAvatars;
13 use BookStack\Users\Models\Role;
14 use BookStack\Users\Models\User;
17 use Illuminate\Support\Facades\Hash;
18 use Illuminate\Support\Facades\Log;
19 use Illuminate\Support\Str;
23 public function __construct(
24 protected UserAvatars $userAvatar,
25 protected UserInviteService $inviteService,
26 protected SlugGenerator $slugGenerator,
31 * Get a user by their email address.
33 public function getByEmail(string $email): ?User
35 return User::query()->where('email', '=', $email)->first();
39 * Get a user by their ID.
41 public function getById(int $id): User
43 return User::query()->findOrFail($id);
47 * Get a user by their slug.
49 public function getBySlug(string $slug): User
51 return User::query()->where('slug', '=', $slug)->firstOrFail();
55 * Create a new basic instance of user with the given pre-validated data.
57 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
59 public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
62 $user->name = $data['name'];
63 $user->email = $data['email'];
64 $user->password = Hash::make(empty($data['password']) ? Str::random(32) : $data['password']);
65 $user->email_confirmed = $emailConfirmed;
66 $user->external_auth_id = $data['external_auth_id'] ?? '';
68 $this->slugGenerator->regenerateForUser($user);
71 if (!empty($data['language'])) {
72 setting()->putUser($user, 'language', $data['language']);
75 if (isset($data['roles'])) {
76 $this->setUserRoles($user, $data['roles']);
79 $this->downloadAndAssignUserAvatar($user);
85 * As per "createWithoutActivity" but records a "create" activity.
87 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
88 * @throws UserInviteException
90 public function create(array $data, bool $sendInvite = false): User
92 $user = $this->createWithoutActivity($data, true);
95 $this->inviteService->sendInvitation($user);
98 Activity::add(ActivityType::USER_CREATE, $user);
104 * Update the given user with the given data, but do not create an activity.
106 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
108 * @throws UserUpdateException
110 public function updateWithoutActivity(User $user, array $data, bool $manageUsersAllowed): User
112 if (!empty($data['name'])) {
113 $user->name = $data['name'];
114 $this->slugGenerator->regenerateForUser($user);
117 if (!empty($data['email']) && $manageUsersAllowed) {
118 $user->email = $data['email'];
121 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
122 $user->external_auth_id = $data['external_auth_id'];
125 if (isset($data['roles']) && $manageUsersAllowed) {
126 $this->setUserRoles($user, $data['roles']);
129 if (!empty($data['password'])) {
130 $user->password = Hash::make($data['password']);
133 if (!empty($data['language'])) {
134 setting()->putUser($user, 'language', $data['language']);
143 * Update the given user with the given data.
145 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
147 * @throws UserUpdateException
149 public function update(User $user, array $data, bool $manageUsersAllowed): User
151 $user = $this->updateWithoutActivity($user, $data, $manageUsersAllowed);
153 Activity::add(ActivityType::USER_UPDATE, $user);
159 * Remove the given user from storage, Delete all related content.
163 public function destroy(User $user, ?int $newOwnerId = null): void
165 $this->ensureDeletable($user);
167 $this->removeUserDependantRelations($user);
168 $this->nullifyUserNonDependantRelations($user);
171 // Delete user profile images
172 $this->userAvatar->destroyAllForUser($user);
174 // Delete related activities
175 setting()->deleteUserSettings($user->id);
177 // Migrate or nullify ownership
179 if (!empty($newOwnerId)) {
180 $newOwner = User::query()->find($newOwnerId);
182 $this->migrateOwnership($user, $newOwner);
184 Activity::add(ActivityType::USER_DELETE, $user);
187 protected function removeUserDependantRelations(User $user): void
189 $user->apiTokens()->delete();
190 $user->socialAccounts()->delete();
191 $user->favourites()->delete();
192 $user->mfaValues()->delete();
193 $user->watches()->delete();
195 $tables = ['email_confirmations', 'user_invites', 'views'];
196 foreach ($tables as $table) {
197 DB::table($table)->where('user_id', '=', $user->id)->delete();
200 protected function nullifyUserNonDependantRelations(User $user): void
203 'attachments' => ['created_by', 'updated_by'],
204 'comments' => ['created_by', 'updated_by'],
205 'deletions' => ['deleted_by'],
206 'entities' => ['created_by', 'updated_by'],
207 'images' => ['created_by', 'updated_by'],
208 'imports' => ['created_by'],
209 'joint_permissions' => ['owner_id'],
210 'page_revisions' => ['created_by'],
211 'sessions' => ['user_id'],
214 foreach ($toNullify as $table => $columns) {
215 foreach ($columns as $column) {
217 ->where($column, '=', $user->id)
218 ->update([$column => null]);
224 * @throws NotifyException
226 protected function ensureDeletable(User $user): void
228 if ($this->isOnlyAdmin($user)) {
229 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
232 if ($user->system_name === 'public') {
233 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
238 * Migrate ownership of items in the system from one user to another.
240 protected function migrateOwnership(User $fromUser, User|null $toUser): void
242 $newOwnerValue = $toUser ? $toUser->id : null;
243 DB::table('entities')
244 ->where('owned_by', '=', $fromUser->id)
245 ->update(['owned_by' => $newOwnerValue]);
249 * Get an avatar image for a user and set it as their avatar.
250 * Returns early if avatars disabled or not set in config.
252 protected function downloadAndAssignUserAvatar(User $user): void
255 $this->userAvatar->fetchAndAssignToUser($user);
256 } catch (Exception $e) {
257 Log::error('Failed to save user avatar image');
262 * Checks if the give user is the only admin.
264 protected function isOnlyAdmin(User $user): bool
266 if (!$user->hasSystemRole('admin')) {
270 $adminRole = Role::getSystemRole('admin');
271 if ($adminRole->users()->count() > 1) {
279 * Set the assigned user roles via an array of role IDs.
281 * @throws UserUpdateException
283 protected function setUserRoles(User $user, array $roles): void
285 $roles = array_filter(array_values($roles));
287 if ($this->demotingLastAdmin($user, $roles)) {
288 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
291 $user->roles()->sync($roles);
295 * Check if the given user is the last admin and their new roles no longer
296 * contain the admin role.
298 protected function demotingLastAdmin(User $user, array $newRoles): bool
300 if ($this->isOnlyAdmin($user)) {
301 $adminRole = Role::getSystemRole('admin');
302 if (!in_array(strval($adminRole->id), $newRoles)) {