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\Image;
12 use BookStack\Uploads\UserAvatars;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Eloquent\Collection;
16 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 all the users with their permissions.
51 public function getAllUsers(): Collection
53 return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
57 * Get all the users with their permissions in a paginated format.
59 public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
61 $sort = $sortData['sort'];
63 $query = User::query()->select(['*'])
64 ->withLastActivityAt()
65 ->with(['roles', 'avatar'])
66 ->orderBy($sort, $sortData['order']);
68 if ($sortData['search']) {
69 $term = '%' . $sortData['search'] . '%';
70 $query->where(function ($query) use ($term) {
71 $query->where('name', 'like', $term)
72 ->orWhere('email', 'like', $term);
76 return $query->paginate($count);
80 * Creates a new user and attaches a role to them.
82 public function registerNew(array $data, bool $emailConfirmed = false): User
84 $user = $this->create($data, $emailConfirmed);
85 $user->attachDefaultRole();
86 $this->downloadAndAssignUserAvatar($user);
92 * Assign a user to a system-level role.
93 * @throws NotFoundException
95 public function attachSystemRole(User $user, string $systemRoleName)
97 $role = Role::getSystemRole($systemRoleName);
99 throw new NotFoundException("Role '{$systemRoleName}' not found");
101 $user->attachRole($role);
105 * Checks if the give user is the only admin.
107 public function isOnlyAdmin(User $user): bool
109 if (!$user->hasSystemRole('admin')) {
113 $adminRole = Role::getSystemRole('admin');
114 if ($adminRole->users()->count() > 1) {
122 * Set the assigned user roles via an array of role IDs.
123 * @throws UserUpdateException
125 public function setUserRoles(User $user, array $roles)
127 if ($this->demotingLastAdmin($user, $roles)) {
128 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
131 $user->roles()->sync($roles);
135 * Check if the given user is the last admin and their new roles no longer
136 * contains the admin role.
138 protected function demotingLastAdmin(User $user, array $newRoles) : bool
140 if ($this->isOnlyAdmin($user)) {
141 $adminRole = Role::getSystemRole('admin');
142 if (!in_array(strval($adminRole->id), $newRoles)) {
151 * Create a new basic instance of user.
153 public function create(array $data, bool $emailConfirmed = false): User
156 'name' => $data['name'],
157 'email' => $data['email'],
158 'password' => bcrypt($data['password']),
159 'email_confirmed' => $emailConfirmed,
160 'external_auth_id' => $data['external_auth_id'] ?? '',
162 return User::query()->forceCreate($details);
166 * Remove the given user from storage, Delete all related content.
169 public function destroy(User $user, ?int $newOwnerId = null)
171 $user->socialAccounts()->delete();
172 $user->apiTokens()->delete();
175 // Delete user profile images
176 $profileImages = Image::query()->where('type', '=', 'user')
177 ->where('uploaded_to', '=', $user->id)
180 foreach ($profileImages as $image) {
181 Images::destroy($image);
184 if (!empty($newOwnerId)) {
185 $newOwner = User::query()->find($newOwnerId);
186 if (!is_null($newOwner)) {
187 $this->migrateOwnership($user, $newOwner);
193 * Migrate ownership of items in the system from one user to another.
195 protected function migrateOwnership(User $fromUser, User $toUser)
197 $entities = (new EntityProvider)->all();
198 foreach ($entities as $instance) {
199 $instance->newQuery()->where('owned_by', '=', $fromUser->id)
200 ->update(['owned_by' => $toUser->id]);
205 * Get the latest activity for a user.
207 public function getActivity(User $user, int $count = 20, int $page = 0): array
209 return Activity::userActivity($user, $count, $page);
213 * Get the recently created content for this given user.
215 public function getRecentlyCreated(User $user, int $count = 20): array
217 $query = function (Builder $query) use ($user, $count) {
218 return $query->orderBy('created_at', 'desc')
219 ->where('created_by', '=', $user->id)
225 'pages' => $query(Page::visible()->where('draft', '=', false)),
226 'chapters' => $query(Chapter::visible()),
227 'books' => $query(Book::visible()),
228 'shelves' => $query(Bookshelf::visible()),
233 * Get asset created counts for the give user.
235 public function getAssetCounts(User $user): array
237 $createdBy = ['created_by' => $user->id];
239 'pages' => Page::visible()->where($createdBy)->count(),
240 'chapters' => Chapter::visible()->where($createdBy)->count(),
241 'books' => Book::visible()->where($createdBy)->count(),
242 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
247 * Get the roles in the system that are assignable to a user.
249 public function getAllRoles(): Collection
251 return Role::query()->orderBy('display_name', 'asc')->get();
255 * Get an avatar image for a user and set it as their avatar.
256 * Returns early if avatars disabled or not set in config.
258 public function downloadAndAssignUserAvatar(User $user): void
261 $this->userAvatar->fetchAndAssignToUser($user);
262 } catch (Exception $e) {
263 Log::error('Failed to save user avatar image');