1 <?php namespace BookStack\Auth;
4 use BookStack\Entities\Book;
5 use BookStack\Entities\Bookshelf;
6 use BookStack\Entities\Chapter;
7 use BookStack\Entities\Page;
8 use BookStack\Exceptions\NotFoundException;
9 use BookStack\Exceptions\UserUpdateException;
10 use BookStack\Uploads\Image;
12 use Illuminate\Database\Eloquent\Builder;
23 * UserRepo constructor.
25 public function __construct(User $user, Role $role)
32 * @param string $email
35 public function getByEmail($email)
37 return $this->user->where('email', '=', $email)->first();
44 public function getById($id)
46 return $this->user->newQuery()->findOrFail($id);
50 * Get all the users with their permissions.
51 * @return Builder|static
53 public function getAllUsers()
55 return $this->user->with('roles', 'avatar')->orderBy('name', 'asc')->get();
59 * Get all the users with their permissions in a paginated format.
62 * @return Builder|static
64 public function getAllUsersPaginatedAndSorted($count, $sortData)
66 $query = $this->user->with('roles', 'avatar')->orderBy($sortData['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 * @param boolean $verifyEmail
85 public function registerNew(array $data, $verifyEmail = false)
87 $user = $this->create($data, $verifyEmail);
88 $this->attachDefaultRole($user);
89 $this->downloadAndAssignUserAvatar($user);
95 * Give a user the default role. Used when creating a new user.
98 public function attachDefaultRole(User $user)
100 $roleId = setting('registration-role');
101 if ($roleId !== false && $user->roles()->where('id', '=', $roleId)->count() === 0) {
102 $user->attachRoleId($roleId);
107 * Assign a user to a system-level role.
109 * @param $systemRoleName
110 * @throws NotFoundException
112 public function attachSystemRole(User $user, $systemRoleName)
114 $role = $this->role->newQuery()->where('system_name', '=', $systemRoleName)->first();
115 if ($role === null) {
116 throw new NotFoundException("Role '{$systemRoleName}' not found");
118 $user->attachRole($role);
122 * Checks if the give user is the only admin.
126 public function isOnlyAdmin(User $user)
128 if (!$user->hasSystemRole('admin')) {
132 $adminRole = $this->role->getSystemRole('admin');
133 if ($adminRole->users->count() > 1) {
140 * Set the assigned user roles via an array of role IDs.
142 * @param array $roles
143 * @throws UserUpdateException
145 public function setUserRoles(User $user, array $roles)
147 if ($this->demotingLastAdmin($user, $roles)) {
148 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
151 $user->roles()->sync($roles);
155 * Check if the given user is the last admin and their new roles no longer
156 * contains the admin role.
158 * @param array $newRoles
161 protected function demotingLastAdmin(User $user, array $newRoles) : bool
163 if ($this->isOnlyAdmin($user)) {
164 $adminRole = $this->role->getSystemRole('admin');
165 if (!in_array(strval($adminRole->id), $newRoles)) {
174 * Create a new basic instance of user.
176 * @param boolean $verifyEmail
179 public function create(array $data, $verifyEmail = false)
181 return $this->user->forceCreate([
182 'name' => $data['name'],
183 'email' => $data['email'],
184 'password' => bcrypt($data['password']),
185 'email_confirmed' => $verifyEmail
190 * Remove the given user from storage, Delete all related content.
194 public function destroy(User $user)
196 $user->socialAccounts()->delete();
199 // Delete user profile images
200 $profileImages = Image::where('type', '=', 'user')->where('uploaded_to', '=', $user->id)->get();
201 foreach ($profileImages as $image) {
202 Images::destroy($image);
207 * Get the latest activity for a user.
213 public function getActivity(User $user, $count = 20, $page = 0)
215 return Activity::userActivity($user, $count, $page);
219 * Get the recently created content for this given user.
221 public function getRecentlyCreated(User $user, int $count = 20): array
223 $query = function (Builder $query) use ($user, $count) {
224 return $query->orderBy('created_at', 'desc')
225 ->where('created_by', '=', $user->id)
231 'pages' => $query(Page::visible()->where('draft', '=', false)),
232 'chapters' => $query(Chapter::visible()),
233 'books' => $query(Book::visible()),
234 'shelves' => $query(Bookshelf::visible()),
239 * Get asset created counts for the give user.
241 public function getAssetCounts(User $user): array
243 $createdBy = ['created_by' => $user->id];
245 'pages' => Page::visible()->where($createdBy)->count(),
246 'chapters' => Chapter::visible()->where($createdBy)->count(),
247 'books' => Book::visible()->where($createdBy)->count(),
248 'shelves' => Bookshelf::visible()->where($createdBy)->count(),
253 * Get the roles in the system that are assignable to a user.
256 public function getAllRoles()
258 return $this->role->newQuery()->orderBy('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.
267 public function downloadAndAssignUserAvatar(User $user)
269 if (!Images::avatarFetchEnabled()) {
274 $avatar = Images::saveUserAvatar($user);
275 $user->avatar()->associate($avatar);
278 } catch (Exception $e) {
279 Log::error('Failed to save user avatar image');