1 <?php namespace BookStack\Auth;
4 use BookStack\Entities\EntityProvider;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Exceptions\NotFoundException;
10 use BookStack\Exceptions\UserUpdateException;
11 use BookStack\Uploads\UserAvatars;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Eloquent\Collection;
15 use Illuminate\Pagination\LengthAwarePaginator;
20 protected $userAvatar;
23 * UserRepo constructor.
25 public function __construct(UserAvatars $userAvatar)
27 $this->userAvatar = $userAvatar;
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 * Get all the users with their permissions.
57 public function getAllUsers(): Collection
59 return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
63 * Get all the users with their permissions in a paginated format.
65 public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
67 $sort = $sortData['sort'];
69 $query = User::query()->select(['*'])
70 ->withLastActivityAt()
71 ->with(['roles', 'avatar'])
72 ->orderBy($sort, $sortData['order']);
74 if ($sortData['search']) {
75 $term = '%' . $sortData['search'] . '%';
76 $query->where(function ($query) use ($term) {
77 $query->where('name', 'like', $term)
78 ->orWhere('email', 'like', $term);
82 return $query->paginate($count);
86 * Creates a new user and attaches a role to them.
88 public function registerNew(array $data, bool $emailConfirmed = false): User
90 $user = $this->create($data, $emailConfirmed);
91 $user->attachDefaultRole();
92 $this->downloadAndAssignUserAvatar($user);
98 * Assign a user to a system-level role.
99 * @throws NotFoundException
101 public function attachSystemRole(User $user, string $systemRoleName)
103 $role = Role::getSystemRole($systemRoleName);
104 if (is_null($role)) {
105 throw new NotFoundException("Role '{$systemRoleName}' not found");
107 $user->attachRole($role);
111 * Checks if the give user is the only admin.
113 public function isOnlyAdmin(User $user): bool
115 if (!$user->hasSystemRole('admin')) {
119 $adminRole = Role::getSystemRole('admin');
120 if ($adminRole->users()->count() > 1) {
128 * Set the assigned user roles via an array of role IDs.
129 * @throws UserUpdateException
131 public function setUserRoles(User $user, array $roles)
133 if ($this->demotingLastAdmin($user, $roles)) {
134 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
137 $user->roles()->sync($roles);
141 * Check if the given user is the last admin and their new roles no longer
142 * contains the admin role.
144 protected function demotingLastAdmin(User $user, array $newRoles) : bool
146 if ($this->isOnlyAdmin($user)) {
147 $adminRole = Role::getSystemRole('admin');
148 if (!in_array(strval($adminRole->id), $newRoles)) {
157 * Create a new basic instance of user.
159 public function create(array $data, bool $emailConfirmed = false): User
162 'name' => $data['name'],
163 'email' => $data['email'],
164 'password' => bcrypt($data['password']),
165 'email_confirmed' => $emailConfirmed,
166 'external_auth_id' => $data['external_auth_id'] ?? '',
170 $user->forceFill($details);
171 $user->refreshSlug();
178 * Remove the given user from storage, Delete all related content.
181 public function destroy(User $user, ?int $newOwnerId = null)
183 $user->socialAccounts()->delete();
184 $user->apiTokens()->delete();
185 $user->favourites()->delete();
188 // Delete user profile images
189 $this->userAvatar->destroyAllForUser($user);
191 if (!empty($newOwnerId)) {
192 $newOwner = User::query()->find($newOwnerId);
193 if (!is_null($newOwner)) {
194 $this->migrateOwnership($user, $newOwner);
200 * Migrate ownership of items in the system from one user to another.
202 protected function migrateOwnership(User $fromUser, User $toUser)
204 $entities = (new EntityProvider)->all();
205 foreach ($entities as $instance) {
206 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
207 ->update(['owned_by' => $toUser->id]);
212 * Get the latest activity for a user.
214 public function getActivity(User $user, int $count = 20, int $page = 0): array
216 return Activity::userActivity($user, $count, $page);
220 * Get the recently created content for this given user.
222 public function getRecentlyCreated(User $user, int $count = 20): array
224 $query = function (Builder $query) use ($user, $count) {
225 return $query->orderBy('created_at', 'desc')
226 ->where('created_by', '=', $user->id)
232 'pages' => $query(Page::visible()->where('draft', '=', false)),
233 'chapters' => $query(Chapter::visible()),
234 'books' => $query(Book::visible()),
235 'shelves' => $query(Bookshelf::visible()),
240 * Get asset created counts for the give user.
242 public function getAssetCounts(User $user): array
244 $createdBy = ['created_by' => $user->id];
246 'pages' => Page::visible()->where($createdBy)->count(),
247 'chapters' => Chapter::visible()->where($createdBy)->count(),
248 'books' => Book::visible()->where($createdBy)->count(),
249 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
254 * Get the roles in the system that are assignable to a user.
256 public function getAllRoles(): Collection
258 return Role::query()->orderBy('display_name', 'asc')->get();
262 * Get an avatar image for a user and set it as their avatar.
263 * Returns early if avatars disabled or not set in config.
265 public function downloadAndAssignUserAvatar(User $user): void
268 $this->userAvatar->fetchAndAssignToUser($user);
269 } catch (Exception $e) {
270 Log::error('Failed to save user avatar image');