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 protected UserAvatars $userAvatar;
22 protected UserInviteService $inviteService;
25 * UserRepo constructor.
27 public function __construct(UserAvatars $userAvatar, UserInviteService $inviteService)
29 $this->userAvatar = $userAvatar;
30 $this->inviteService = $inviteService;
34 * Get a user by their email address.
36 public function getByEmail(string $email): ?User
38 return User::query()->where('email', '=', $email)->first();
42 * Get a user by their ID.
44 public function getById(int $id): User
46 return User::query()->findOrFail($id);
50 * Get a user by their slug.
52 public function getBySlug(string $slug): User
54 return User::query()->where('slug', '=', $slug)->firstOrFail();
58 * Create a new basic instance of user with the given pre-validated data.
60 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
62 public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
65 $user->name = $data['name'];
66 $user->email = $data['email'];
67 $user->password = Hash::make(empty($data['password']) ? Str::random(32) : $data['password']);
68 $user->email_confirmed = $emailConfirmed;
69 $user->external_auth_id = $data['external_auth_id'] ?? '';
74 if (!empty($data['language'])) {
75 setting()->putUser($user, 'language', $data['language']);
78 if (isset($data['roles'])) {
79 $this->setUserRoles($user, $data['roles']);
82 $this->downloadAndAssignUserAvatar($user);
88 * As per "createWithoutActivity" but records a "create" activity.
90 * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
92 public function create(array $data, bool $sendInvite = false): User
94 $user = $this->createWithoutActivity($data, true);
97 $this->inviteService->sendInvitation($user);
100 Activity::add(ActivityType::USER_CREATE, $user);
106 * Update the given user with the given data.
108 * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
110 * @throws UserUpdateException
112 public function update(User $user, array $data, bool $manageUsersAllowed): User
114 if (!empty($data['name'])) {
115 $user->name = $data['name'];
116 $user->refreshSlug();
119 if (!empty($data['email']) && $manageUsersAllowed) {
120 $user->email = $data['email'];
123 if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
124 $user->external_auth_id = $data['external_auth_id'];
127 if (isset($data['roles']) && $manageUsersAllowed) {
128 $this->setUserRoles($user, $data['roles']);
131 if (!empty($data['password'])) {
132 $user->password = Hash::make($data['password']);
135 if (!empty($data['language'])) {
136 setting()->putUser($user, 'language', $data['language']);
140 Activity::add(ActivityType::USER_UPDATE, $user);
146 * Remove the given user from storage, Delete all related content.
150 public function destroy(User $user, ?int $newOwnerId = null)
152 $this->ensureDeletable($user);
154 $user->socialAccounts()->delete();
155 $user->apiTokens()->delete();
156 $user->favourites()->delete();
157 $user->mfaValues()->delete();
160 // Delete user profile images
161 $this->userAvatar->destroyAllForUser($user);
163 // Delete related activities
164 setting()->deleteUserSettings($user->id);
166 if (!empty($newOwnerId)) {
167 $newOwner = User::query()->find($newOwnerId);
168 if (!is_null($newOwner)) {
169 $this->migrateOwnership($user, $newOwner);
173 Activity::add(ActivityType::USER_DELETE, $user);
177 * @throws NotifyException
179 protected function ensureDeletable(User $user): void
181 if ($this->isOnlyAdmin($user)) {
182 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
185 if ($user->system_name === 'public') {
186 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
191 * Migrate ownership of items in the system from one user to another.
193 protected function migrateOwnership(User $fromUser, User $toUser)
195 $entities = (new EntityProvider())->all();
196 foreach ($entities as $instance) {
197 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
198 ->update(['owned_by' => $toUser->id]);
203 * Get an avatar image for a user and set it as their avatar.
204 * Returns early if avatars disabled or not set in config.
206 protected function downloadAndAssignUserAvatar(User $user): void
209 $this->userAvatar->fetchAndAssignToUser($user);
210 } catch (Exception $e) {
211 Log::error('Failed to save user avatar image');
216 * Checks if the give user is the only admin.
218 protected function isOnlyAdmin(User $user): bool
220 if (!$user->hasSystemRole('admin')) {
224 $adminRole = Role::getSystemRole('admin');
225 if ($adminRole->users()->count() > 1) {
233 * Set the assigned user roles via an array of role IDs.
235 * @throws UserUpdateException
237 protected function setUserRoles(User $user, array $roles)
239 $roles = array_filter(array_values($roles));
241 if ($this->demotingLastAdmin($user, $roles)) {
242 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
245 $user->roles()->sync($roles);
249 * Check if the given user is the last admin and their new roles no longer
250 * contains the admin role.
252 protected function demotingLastAdmin(User $user, array $newRoles): bool
254 if ($this->isOnlyAdmin($user)) {
255 $adminRole = Role::getSystemRole('admin');
256 if (!in_array(strval($adminRole->id), $newRoles)) {