3 namespace BookStack\Users;
5 use BookStack\Access\UserInviteService;
6 use BookStack\Activity\ActivityType;
7 use BookStack\Entities\EntityProvider;
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;
15 use Illuminate\Support\Facades\Hash;
16 use Illuminate\Support\Facades\Log;
17 use Illuminate\Support\Str;
21 public function __construct(
22 protected UserAvatars $userAvatar,
23 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
87 public function create(array $data, bool $sendInvite = false): User
89 $user = $this->createWithoutActivity($data, true);
92 $this->inviteService->sendInvitation($user);
95 Activity::add(ActivityType::USER_CREATE, $user);
101 * Update the given user with the given data.
103 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
105 * @throws UserUpdateException
107 public function update(User $user, array $data, bool $manageUsersAllowed): User
109 if (!empty($data['name'])) {
110 $user->name = $data['name'];
111 $user->refreshSlug();
114 if (!empty($data['email']) && $manageUsersAllowed) {
115 $user->email = $data['email'];
118 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
119 $user->external_auth_id = $data['external_auth_id'];
122 if (isset($data['roles']) && $manageUsersAllowed) {
123 $this->setUserRoles($user, $data['roles']);
126 if (!empty($data['password'])) {
127 $user->password = Hash::make($data['password']);
130 if (!empty($data['language'])) {
131 setting()->putUser($user, 'language', $data['language']);
135 Activity::add(ActivityType::USER_UPDATE, $user);
141 * Remove the given user from storage, Delete all related content.
145 public function destroy(User $user, ?int $newOwnerId = null)
147 $this->ensureDeletable($user);
149 $user->socialAccounts()->delete();
150 $user->apiTokens()->delete();
151 $user->favourites()->delete();
152 $user->mfaValues()->delete();
153 $user->watches()->delete();
156 // Delete user profile images
157 $this->userAvatar->destroyAllForUser($user);
159 // Delete related activities
160 setting()->deleteUserSettings($user->id);
162 if (!empty($newOwnerId)) {
163 $newOwner = User::query()->find($newOwnerId);
164 if (!is_null($newOwner)) {
165 $this->migrateOwnership($user, $newOwner);
169 Activity::add(ActivityType::USER_DELETE, $user);
173 * @throws NotifyException
175 protected function ensureDeletable(User $user): void
177 if ($this->isOnlyAdmin($user)) {
178 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
181 if ($user->system_name === 'public') {
182 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
187 * Migrate ownership of items in the system from one user to another.
189 protected function migrateOwnership(User $fromUser, User $toUser)
191 $entities = (new EntityProvider())->all();
192 foreach ($entities as $instance) {
193 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
194 ->update(['owned_by' => $toUser->id]);
199 * Get an avatar image for a user and set it as their avatar.
200 * Returns early if avatars disabled or not set in config.
202 protected function downloadAndAssignUserAvatar(User $user): void
205 $this->userAvatar->fetchAndAssignToUser($user);
206 } catch (Exception $e) {
207 Log::error('Failed to save user avatar image');
212 * Checks if the give user is the only admin.
214 protected function isOnlyAdmin(User $user): bool
216 if (!$user->hasSystemRole('admin')) {
220 $adminRole = Role::getSystemRole('admin');
221 if ($adminRole->users()->count() > 1) {
229 * Set the assigned user roles via an array of role IDs.
231 * @throws UserUpdateException
233 protected function setUserRoles(User $user, array $roles)
235 $roles = array_filter(array_values($roles));
237 if ($this->demotingLastAdmin($user, $roles)) {
238 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
241 $user->roles()->sync($roles);
245 * Check if the given user is the last admin and their new roles no longer
246 * contains the admin role.
248 protected function demotingLastAdmin(User $user, array $newRoles): bool
250 if ($this->isOnlyAdmin($user)) {
251 $adminRole = Role::getSystemRole('admin');
252 if (!in_array(strval($adminRole->id), $newRoles)) {