3 namespace BookStack\Auth;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\UserInviteService;
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;
13 use Illuminate\Support\Facades\Log;
14 use Illuminate\Support\Str;
18 protected UserAvatars $userAvatar;
19 protected UserInviteService $inviteService;
22 * UserRepo constructor.
24 public function __construct(UserAvatars $userAvatar, UserInviteService $inviteService)
26 $this->userAvatar = $userAvatar;
27 $this->inviteService = $inviteService;
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 = bcrypt(empty($data['password']) ? Str::random(32) : $data['password']);
65 $user->email_confirmed = $emailConfirmed;
66 $user->external_auth_id = $data['external_auth_id'] ?? '';
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
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 = bcrypt($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();
157 // Delete user profile images
158 $this->userAvatar->destroyAllForUser($user);
160 if (!empty($newOwnerId)) {
161 $newOwner = User::query()->find($newOwnerId);
162 if (!is_null($newOwner)) {
163 $this->migrateOwnership($user, $newOwner);
167 Activity::add(ActivityType::USER_DELETE, $user);
171 * @throws NotifyException
173 protected function ensureDeletable(User $user): void
175 if ($this->isOnlyAdmin($user)) {
176 throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
179 if ($user->system_name === 'public') {
180 throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
185 * Migrate ownership of items in the system from one user to another.
187 protected function migrateOwnership(User $fromUser, User $toUser)
189 $entities = (new EntityProvider())->all();
190 foreach ($entities as $instance) {
191 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
192 ->update(['owned_by' => $toUser->id]);
197 * Get an avatar image for a user and set it as their avatar.
198 * Returns early if avatars disabled or not set in config.
200 protected function downloadAndAssignUserAvatar(User $user): void
203 $this->userAvatar->fetchAndAssignToUser($user);
204 } catch (Exception $e) {
205 Log::error('Failed to save user avatar image');
210 * Checks if the give user is the only admin.
212 protected function isOnlyAdmin(User $user): bool
214 if (!$user->hasSystemRole('admin')) {
218 $adminRole = Role::getSystemRole('admin');
219 if ($adminRole->users()->count() > 1) {
227 * Set the assigned user roles via an array of role IDs.
229 * @throws UserUpdateException
231 protected function setUserRoles(User $user, array $roles)
233 if ($this->demotingLastAdmin($user, $roles)) {
234 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
237 $user->roles()->sync($roles);
241 * Check if the given user is the last admin and their new roles no longer
242 * contains the admin role.
244 protected function demotingLastAdmin(User $user, array $newRoles): bool
246 if ($this->isOnlyAdmin($user)) {
247 $adminRole = Role::getSystemRole('admin');
248 if (!in_array(strval($adminRole->id), $newRoles)) {