3 namespace BookStack\Auth;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Exceptions\NotFoundException;
11 use BookStack\Exceptions\UserUpdateException;
12 use BookStack\Uploads\UserAvatars;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Eloquent\Collection;
16 use Illuminate\Pagination\LengthAwarePaginator;
17 use Illuminate\Support\Facades\Log;
21 protected $userAvatar;
24 * UserRepo constructor.
26 public function __construct(UserAvatars $userAvatar)
28 $this->userAvatar = $userAvatar;
32 * Get a user by their email address.
34 public function getByEmail(string $email): ?User
36 return User::query()->where('email', '=', $email)->first();
40 * Get a user by their ID.
42 public function getById(int $id): User
44 return User::query()->findOrFail($id);
48 * Get a user by their slug.
50 public function getBySlug(string $slug): User
52 return User::query()->where('slug', '=', $slug)->firstOrFail();
56 * Get all the users with their permissions.
58 public function getAllUsers(): Collection
60 return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
64 * Get all the users with their permissions in a paginated format.
65 * Note: Due to the use of email search this should only be used when
66 * user is assumed to be trusted. (Admin users).
67 * Email search can be abused to extract email addresses.
69 public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
71 $sort = $sortData['sort'];
73 $query = User::query()->select(['*'])
74 ->scopes(['withLastActivityAt'])
75 ->with(['roles', 'avatar'])
76 ->withCount('mfaValues')
77 ->orderBy($sort, $sortData['order']);
79 if ($sortData['search']) {
80 $term = '%' . $sortData['search'] . '%';
81 $query->where(function ($query) use ($term) {
82 $query->where('name', 'like', $term)
83 ->orWhere('email', 'like', $term);
87 return $query->paginate($count);
91 * Creates a new user and attaches a role to them.
93 public function registerNew(array $data, bool $emailConfirmed = false): User
95 $user = $this->create($data, $emailConfirmed);
96 $user->attachDefaultRole();
97 $this->downloadAndAssignUserAvatar($user);
103 * Assign a user to a system-level role.
105 * @throws NotFoundException
107 public function attachSystemRole(User $user, string $systemRoleName)
109 $role = Role::getSystemRole($systemRoleName);
110 if (is_null($role)) {
111 throw new NotFoundException("Role '{$systemRoleName}' not found");
113 $user->attachRole($role);
117 * Checks if the give user is the only admin.
119 public function isOnlyAdmin(User $user): bool
121 if (!$user->hasSystemRole('admin')) {
125 $adminRole = Role::getSystemRole('admin');
126 if ($adminRole->users()->count() > 1) {
134 * Set the assigned user roles via an array of role IDs.
136 * @throws UserUpdateException
138 public function setUserRoles(User $user, array $roles)
140 if ($this->demotingLastAdmin($user, $roles)) {
141 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
144 $user->roles()->sync($roles);
148 * Check if the given user is the last admin and their new roles no longer
149 * contains the admin role.
151 protected function demotingLastAdmin(User $user, array $newRoles): bool
153 if ($this->isOnlyAdmin($user)) {
154 $adminRole = Role::getSystemRole('admin');
155 if (!in_array(strval($adminRole->id), $newRoles)) {
164 * Create a new basic instance of user.
166 public function create(array $data, bool $emailConfirmed = false): User
169 'name' => $data['name'],
170 'email' => $data['email'],
171 'password' => bcrypt($data['password']),
172 'email_confirmed' => $emailConfirmed,
173 'external_auth_id' => $data['external_auth_id'] ?? '',
177 $user->forceFill($details);
178 $user->refreshSlug();
185 * Remove the given user from storage, Delete all related content.
189 public function destroy(User $user, ?int $newOwnerId = null)
191 $user->socialAccounts()->delete();
192 $user->apiTokens()->delete();
193 $user->favourites()->delete();
194 $user->mfaValues()->delete();
197 // Delete user profile images
198 $this->userAvatar->destroyAllForUser($user);
200 if (!empty($newOwnerId)) {
201 $newOwner = User::query()->find($newOwnerId);
202 if (!is_null($newOwner)) {
203 $this->migrateOwnership($user, $newOwner);
209 * Migrate ownership of items in the system from one user to another.
211 protected function migrateOwnership(User $fromUser, User $toUser)
213 $entities = (new EntityProvider())->all();
214 foreach ($entities as $instance) {
215 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
216 ->update(['owned_by' => $toUser->id]);
221 * Get the recently created content for this given user.
223 public function getRecentlyCreated(User $user, int $count = 20): array
225 $query = function (Builder $query) use ($user, $count) {
226 return $query->orderBy('created_at', 'desc')
227 ->where('created_by', '=', $user->id)
233 'pages' => $query(Page::visible()->where('draft', '=', false)),
234 'chapters' => $query(Chapter::visible()),
235 'books' => $query(Book::visible()),
236 'shelves' => $query(Bookshelf::visible()),
241 * Get asset created counts for the give user.
243 public function getAssetCounts(User $user): array
245 $createdBy = ['created_by' => $user->id];
248 'pages' => Page::visible()->where($createdBy)->count(),
249 'chapters' => Chapter::visible()->where($createdBy)->count(),
250 'books' => Book::visible()->where($createdBy)->count(),
251 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
256 * Get the roles in the system that are assignable to a user.
258 public function getAllRoles(): Collection
260 return Role::query()->orderBy('display_name', 'asc')->get();
264 * Get an avatar image for a user and set it as their avatar.
265 * Returns early if avatars disabled or not set in config.
267 public function downloadAndAssignUserAvatar(User $user): void
270 $this->userAvatar->fetchAndAssignToUser($user);
271 } catch (Exception $e) {
272 Log::error('Failed to save user avatar image');