3 namespace BookStack\Users;
5 use BookStack\Access\UserInviteException;
6 use BookStack\Access\UserInviteService;
7 use BookStack\Activity\ActivityType;
8 use BookStack\Entities\EntityProvider;
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;
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
30 * Get a user by their email address.
32 public function getByEmail(string $email): ?User
34 return User::query()->where('email', '=', $email)->first();
38 * Get a user by their ID.
40 public function getById(int $id): User
42 return User::query()->findOrFail($id);
46 * Get a user by their slug.
48 public function getBySlug(string $slug): User
50 return User::query()->where('slug', '=', $slug)->firstOrFail();
54 * Create a new basic instance of user with the given pre-validated data.
56 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
58 public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
61 $user->name = $data['name'];
62 $user->email = $data['email'];
63 $user->password = Hash::make(empty($data['password']) ? Str::random(32) : $data['password']);
64 $user->email_confirmed = $emailConfirmed;
65 $user->external_auth_id = $data['external_auth_id'] ?? '';
70 if (!empty($data['language'])) {
71 setting()->putUser($user, 'language', $data['language']);
74 if (isset($data['roles'])) {
75 $this->setUserRoles($user, $data['roles']);
78 $this->downloadAndAssignUserAvatar($user);
84 * As per "createWithoutActivity" but records a "create" activity.
86 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
87 * @throws UserInviteException
89 public function create(array $data, bool $sendInvite = false): User
91 $user = $this->createWithoutActivity($data, true);
94 $this->inviteService->sendInvitation($user);
97 Activity::add(ActivityType::USER_CREATE, $user);
103 * Update the given user with the given data.
105 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
107 * @throws UserUpdateException
109 public function update(User $user, array $data, bool $manageUsersAllowed): User
111 if (!empty($data['name'])) {
112 $user->name = $data['name'];
113 $user->refreshSlug();
116 if (!empty($data['email']) && $manageUsersAllowed) {
117 $user->email = $data['email'];
120 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
121 $user->external_auth_id = $data['external_auth_id'];
124 if (isset($data['roles']) && $manageUsersAllowed) {
125 $this->setUserRoles($user, $data['roles']);
128 if (!empty($data['password'])) {
129 $user->password = Hash::make($data['password']);
132 if (!empty($data['language'])) {
133 setting()->putUser($user, 'language', $data['language']);
137 Activity::add(ActivityType::USER_UPDATE, $user);
143 * Remove the given user from storage, Delete all related content.
147 public function destroy(User $user, ?int $newOwnerId = null)
149 $this->ensureDeletable($user);
151 $user->socialAccounts()->delete();
152 $user->apiTokens()->delete();
153 $user->favourites()->delete();
154 $user->mfaValues()->delete();
155 $user->watches()->delete();
158 // Delete user profile images
159 $this->userAvatar->destroyAllForUser($user);
161 // Delete related activities
162 setting()->deleteUserSettings($user->id);
164 if (!empty($newOwnerId)) {
165 $newOwner = User::query()->find($newOwnerId);
166 if (!is_null($newOwner)) {
167 $this->migrateOwnership($user, $newOwner);
171 Activity::add(ActivityType::USER_DELETE, $user);
175 * @throws NotifyException
177 protected function ensureDeletable(User $user): void
179 if ($this->isOnlyAdmin($user)) {
180 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
183 if ($user->system_name === 'public') {
184 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
189 * Migrate ownership of items in the system from one user to another.
191 protected function migrateOwnership(User $fromUser, User $toUser)
193 $entities = (new EntityProvider())->all();
194 foreach ($entities as $instance) {
195 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
196 ->update(['owned_by' => $toUser->id]);
201 * Get an avatar image for a user and set it as their avatar.
202 * Returns early if avatars disabled or not set in config.
204 protected function downloadAndAssignUserAvatar(User $user): void
207 $this->userAvatar->fetchAndAssignToUser($user);
208 } catch (Exception $e) {
209 Log::error('Failed to save user avatar image');
214 * Checks if the give user is the only admin.
216 protected function isOnlyAdmin(User $user): bool
218 if (!$user->hasSystemRole('admin')) {
222 $adminRole = Role::getSystemRole('admin');
223 if ($adminRole->users()->count() > 1) {
231 * Set the assigned user roles via an array of role IDs.
233 * @throws UserUpdateException
235 protected function setUserRoles(User $user, array $roles)
237 $roles = array_filter(array_values($roles));
239 if ($this->demotingLastAdmin($user, $roles)) {
240 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
243 $user->roles()->sync($roles);
247 * Check if the given user is the last admin and their new roles no longer
248 * contains the admin role.
250 protected function demotingLastAdmin(User $user, array $newRoles): bool
252 if ($this->isOnlyAdmin($user)) {
253 $adminRole = Role::getSystemRole('admin');
254 if (!in_array(strval($adminRole->id), $newRoles)) {