1 <?php namespace BookStack\Auth;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Bookshelf;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Exceptions\NotFoundException;
9 use BookStack\Exceptions\UserUpdateException;
10 use BookStack\Uploads\Image;
11 use BookStack\Uploads\UserAvatars;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Eloquent\Collection;
15 use Illuminate\Pagination\LengthAwarePaginator;
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 all the users with their permissions.
50 public function getAllUsers(): Collection
52 return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
56 * Get all the users with their permissions in a paginated format.
58 public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
60 $sort = $sortData['sort'];
61 if ($sort === 'latest_activity') {
62 $sort = \BookStack\Actions\Activity::query()->select('created_at')
63 ->whereColumn('activities.user_id', 'users.id')
68 $query = User::query()->with(['roles', 'avatar', 'latestActivity'])
69 ->orderBy($sort, $sortData['order']);
71 if ($sortData['search']) {
72 $term = '%' . $sortData['search'] . '%';
73 $query->where(function ($query) use ($term) {
74 $query->where('name', 'like', $term)
75 ->orWhere('email', 'like', $term);
79 return $query->paginate($count);
83 * Creates a new user and attaches a role to them.
85 public function registerNew(array $data, bool $emailConfirmed = false): User
87 $user = $this->create($data, $emailConfirmed);
88 $user->attachDefaultRole();
89 $this->downloadAndAssignUserAvatar($user);
95 * Assign a user to a system-level role.
96 * @throws NotFoundException
98 public function attachSystemRole(User $user, string $systemRoleName)
100 $role = Role::getSystemRole($systemRoleName);
101 if (is_null($role)) {
102 throw new NotFoundException("Role '{$systemRoleName}' not found");
104 $user->attachRole($role);
108 * Checks if the give user is the only admin.
110 public function isOnlyAdmin(User $user): bool
112 if (!$user->hasSystemRole('admin')) {
116 $adminRole = Role::getSystemRole('admin');
117 if ($adminRole->users()->count() > 1) {
125 * Set the assigned user roles via an array of role IDs.
126 * @throws UserUpdateException
128 public function setUserRoles(User $user, array $roles)
130 if ($this->demotingLastAdmin($user, $roles)) {
131 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
134 $user->roles()->sync($roles);
138 * Check if the given user is the last admin and their new roles no longer
139 * contains the admin role.
141 protected function demotingLastAdmin(User $user, array $newRoles) : bool
143 if ($this->isOnlyAdmin($user)) {
144 $adminRole = Role::getSystemRole('admin');
145 if (!in_array(strval($adminRole->id), $newRoles)) {
154 * Create a new basic instance of user.
156 public function create(array $data, bool $emailConfirmed = false): User
159 'name' => $data['name'],
160 'email' => $data['email'],
161 'password' => bcrypt($data['password']),
162 'email_confirmed' => $emailConfirmed,
163 'external_auth_id' => $data['external_auth_id'] ?? '',
165 return User::query()->forceCreate($details);
169 * Remove the given user from storage, Delete all related content.
172 public function destroy(User $user)
174 $user->socialAccounts()->delete();
175 $user->apiTokens()->delete();
178 // Delete user profile images
179 $profileImages = Image::query()->where('type', '=', 'user')
180 ->where('uploaded_to', '=', $user->id)
183 foreach ($profileImages as $image) {
184 Images::destroy($image);
189 * Get the latest activity for a user.
191 public function getActivity(User $user, int $count = 20, int $page = 0): array
193 return Activity::userActivity($user, $count, $page);
197 * Get the recently created content for this given user.
199 public function getRecentlyCreated(User $user, int $count = 20): array
201 $query = function (Builder $query) use ($user, $count) {
202 return $query->orderBy('created_at', 'desc')
203 ->where('created_by', '=', $user->id)
209 'pages' => $query(Page::visible()->where('draft', '=', false)),
210 'chapters' => $query(Chapter::visible()),
211 'books' => $query(Book::visible()),
212 'shelves' => $query(Bookshelf::visible()),
217 * Get asset created counts for the give user.
219 public function getAssetCounts(User $user): array
221 $createdBy = ['created_by' => $user->id];
223 'pages' => Page::visible()->where($createdBy)->count(),
224 'chapters' => Chapter::visible()->where($createdBy)->count(),
225 'books' => Book::visible()->where($createdBy)->count(),
226 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
231 * Get the roles in the system that are assignable to a user.
233 public function getAllRoles(): Collection
235 return Role::query()->orderBy('display_name', 'asc')->get();
239 * Get an avatar image for a user and set it as their avatar.
240 * Returns early if avatars disabled or not set in config.
242 public function downloadAndAssignUserAvatar(User $user): void
245 $this->userAvatar->fetchAndAssignToUser($user);
246 } catch (Exception $e) {
247 Log::error('Failed to save user avatar image');