3 namespace BookStack\Auth;
6 use BookStack\Entities\EntityProvider;
7 use BookStack\Entities\Models\Book;
8 use BookStack\Entities\Models\Bookshelf;
9 use BookStack\Entities\Models\Chapter;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Exceptions\NotFoundException;
12 use BookStack\Exceptions\UserUpdateException;
13 use BookStack\Uploads\UserAvatars;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Database\Eloquent\Collection;
17 use Illuminate\Pagination\LengthAwarePaginator;
22 protected $userAvatar;
25 * UserRepo constructor.
27 public function __construct(UserAvatars $userAvatar)
29 $this->userAvatar = $userAvatar;
33 * Get a user by their email address.
35 public function getByEmail(string $email): ?User
37 return User::query()->where('email', '=', $email)->first();
41 * Get a user by their ID.
43 public function getById(int $id): User
45 return User::query()->findOrFail($id);
49 * Get a user by their slug.
51 public function getBySlug(string $slug): User
53 return User::query()->where('slug', '=', $slug)->firstOrFail();
57 * Get all the users with their permissions.
59 public function getAllUsers(): Collection
61 return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
65 * Get all the users with their permissions in a paginated format.
67 public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
69 $sort = $sortData['sort'];
71 $query = User::query()->select(['*'])
72 ->withLastActivityAt()
73 ->with(['roles', 'avatar'])
74 ->withCount('mfaValues')
75 ->orderBy($sort, $sortData['order']);
77 if ($sortData['search']) {
78 $term = '%' . $sortData['search'] . '%';
79 $query->where(function ($query) use ($term) {
80 $query->where('name', 'like', $term)
81 ->orWhere('email', 'like', $term);
85 return $query->paginate($count);
89 * Creates a new user and attaches a role to them.
91 public function registerNew(array $data, bool $emailConfirmed = false): User
93 $user = $this->create($data, $emailConfirmed);
94 $user->attachDefaultRole();
95 $this->downloadAndAssignUserAvatar($user);
101 * Assign a user to a system-level role.
103 * @throws NotFoundException
105 public function attachSystemRole(User $user, string $systemRoleName)
107 $role = Role::getSystemRole($systemRoleName);
108 if (is_null($role)) {
109 throw new NotFoundException("Role '{$systemRoleName}' not found");
111 $user->attachRole($role);
115 * Checks if the give user is the only admin.
117 public function isOnlyAdmin(User $user): bool
119 if (!$user->hasSystemRole('admin')) {
123 $adminRole = Role::getSystemRole('admin');
124 if ($adminRole->users()->count() > 1) {
132 * Set the assigned user roles via an array of role IDs.
134 * @throws UserUpdateException
136 public function setUserRoles(User $user, array $roles)
138 if ($this->demotingLastAdmin($user, $roles)) {
139 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
142 $user->roles()->sync($roles);
146 * Check if the given user is the last admin and their new roles no longer
147 * contains the admin role.
149 protected function demotingLastAdmin(User $user, array $newRoles): bool
151 if ($this->isOnlyAdmin($user)) {
152 $adminRole = Role::getSystemRole('admin');
153 if (!in_array(strval($adminRole->id), $newRoles)) {
162 * Create a new basic instance of user.
164 public function create(array $data, bool $emailConfirmed = false): User
167 'name' => $data['name'],
168 'email' => $data['email'],
169 'password' => bcrypt($data['password']),
170 'email_confirmed' => $emailConfirmed,
171 'external_auth_id' => $data['external_auth_id'] ?? '',
175 $user->forceFill($details);
176 $user->refreshSlug();
183 * Remove the given user from storage, Delete all related content.
187 public function destroy(User $user, ?int $newOwnerId = null)
189 $user->socialAccounts()->delete();
190 $user->apiTokens()->delete();
191 $user->favourites()->delete();
192 $user->mfaValues()->delete();
195 // Delete user profile images
196 $this->userAvatar->destroyAllForUser($user);
198 if (!empty($newOwnerId)) {
199 $newOwner = User::query()->find($newOwnerId);
200 if (!is_null($newOwner)) {
201 $this->migrateOwnership($user, $newOwner);
207 * Migrate ownership of items in the system from one user to another.
209 protected function migrateOwnership(User $fromUser, User $toUser)
211 $entities = (new EntityProvider())->all();
212 foreach ($entities as $instance) {
213 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
214 ->update(['owned_by' => $toUser->id]);
219 * Get the latest activity for a user.
221 public function getActivity(User $user, int $count = 20, int $page = 0): array
223 return Activity::userActivity($user, $count, $page);
227 * Get the recently created content for this given user.
229 public function getRecentlyCreated(User $user, int $count = 20): array
231 $query = function (Builder $query) use ($user, $count) {
232 return $query->orderBy('created_at', 'desc')
233 ->where('created_by', '=', $user->id)
239 'pages' => $query(Page::visible()->where('draft', '=', false)),
240 'chapters' => $query(Chapter::visible()),
241 'books' => $query(Book::visible()),
242 'shelves' => $query(Bookshelf::visible()),
247 * Get asset created counts for the give user.
249 public function getAssetCounts(User $user): array
251 $createdBy = ['created_by' => $user->id];
254 'pages' => Page::visible()->where($createdBy)->count(),
255 'chapters' => Chapter::visible()->where($createdBy)->count(),
256 'books' => Book::visible()->where($createdBy)->count(),
257 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
262 * Get the roles in the system that are assignable to a user.
264 public function getAllRoles(): Collection
266 return Role::query()->orderBy('display_name', 'asc')->get();
270 * Get an avatar image for a user and set it as their avatar.
271 * Returns early if avatars disabled or not set in config.
273 public function downloadAndAssignUserAvatar(User $user): void
276 $this->userAvatar->fetchAndAssignToUser($user);
277 } catch (Exception $e) {
278 Log::error('Failed to save user avatar image');