1 <?php namespace BookStack\Auth;
4 use BookStack\Entities\Repos\EntityRepo;
5 use BookStack\Exceptions\NotFoundException;
6 use BookStack\Exceptions\UserUpdateException;
7 use BookStack\Uploads\Image;
9 use Illuminate\Database\Eloquent\Builder;
17 protected $entityRepo;
20 * UserRepo constructor.
23 * @param EntityRepo $entityRepo
25 public function __construct(User $user, Role $role, EntityRepo $entityRepo)
29 $this->entityRepo = $entityRepo;
33 * @param string $email
36 public function getByEmail($email)
38 return $this->user->where('email', '=', $email)->first();
45 public function getById($id)
47 return $this->user->newQuery()->findOrFail($id);
51 * Get all the users with their permissions.
52 * @return Builder|static
54 public function getAllUsers()
56 return $this->user->with('roles', 'avatar')->orderBy('name', 'asc')->get();
60 * Get all the users with their permissions in a paginated format.
63 * @return Builder|static
65 public function getAllUsersPaginatedAndSorted($count, $sortData)
67 $query = $this->user->with('roles', 'avatar')->orderBy($sortData['sort'], $sortData['order']);
69 if ($sortData['search']) {
70 $term = '%' . $sortData['search'] . '%';
71 $query->where(function ($query) use ($term) {
72 $query->where('name', 'like', $term)
73 ->orWhere('email', 'like', $term);
77 return $query->paginate($count);
81 * Creates a new user and attaches a role to them.
83 * @param boolean $verifyEmail
84 * @return \BookStack\Auth\User
86 public function registerNew(array $data, $verifyEmail = false)
88 $user = $this->create($data, $verifyEmail);
89 $this->attachDefaultRole($user);
90 $this->downloadAndAssignUserAvatar($user);
96 * Give a user the default role. Used when creating a new user.
99 public function attachDefaultRole(User $user)
101 $roleId = setting('registration-role');
102 if ($roleId !== false && $user->roles()->where('id', '=', $roleId)->count() === 0) {
103 $user->attachRoleId($roleId);
108 * Assign a user to a system-level role.
110 * @param $systemRoleName
111 * @throws NotFoundException
113 public function attachSystemRole(User $user, $systemRoleName)
115 $role = $this->role->newQuery()->where('system_name', '=', $systemRoleName)->first();
116 if ($role === null) {
117 throw new NotFoundException("Role '{$systemRoleName}' not found");
119 $user->attachRole($role);
123 * Checks if the give user is the only admin.
124 * @param \BookStack\Auth\User $user
127 public function isOnlyAdmin(User $user)
129 if (!$user->hasSystemRole('admin')) {
133 $adminRole = $this->role->getSystemRole('admin');
134 if ($adminRole->users->count() > 1) {
141 * Set the assigned user roles via an array of role IDs.
143 * @param array $roles
144 * @throws UserUpdateException
146 public function setUserRoles(User $user, array $roles)
148 if ($this->demotingLastAdmin($user, $roles)) {
149 throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
152 $user->roles()->sync($roles);
156 * Check if the given user is the last admin and their new roles no longer
157 * contains the admin role.
159 * @param array $newRoles
162 protected function demotingLastAdmin(User $user, array $newRoles) : bool
164 if ($this->isOnlyAdmin($user)) {
165 $adminRole = $this->role->getSystemRole('admin');
166 if (!in_array(strval($adminRole->id), $newRoles)) {
175 * Create a new basic instance of user.
177 * @param boolean $verifyEmail
178 * @return \BookStack\Auth\User
180 public function create(array $data, $verifyEmail = false)
182 return $this->user->forceCreate([
183 'name' => $data['name'],
184 'email' => $data['email'],
185 'password' => bcrypt($data['password']),
186 'email_confirmed' => $verifyEmail
191 * Remove the given user from storage, Delete all related content.
192 * @param \BookStack\Auth\User $user
195 public function destroy(User $user)
197 $user->socialAccounts()->delete();
200 // Delete user profile images
201 $profileImages = Image::where('type', '=', 'user')->where('uploaded_to', '=', $user->id)->get();
202 foreach ($profileImages as $image) {
203 Images::destroy($image);
208 * Get the latest activity for a user.
209 * @param \BookStack\Auth\User $user
214 public function getActivity(User $user, $count = 20, $page = 0)
216 return Activity::userActivity($user, $count, $page);
220 * Get the recently created content for this given user.
221 * @param \BookStack\Auth\User $user
225 public function getRecentlyCreated(User $user, $count = 20)
227 $createdByUserQuery = function (Builder $query) use ($user) {
228 $query->where('created_by', '=', $user->id);
232 'pages' => $this->entityRepo->getRecentlyCreated('page', $count, 0, $createdByUserQuery),
233 'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, $createdByUserQuery),
234 'books' => $this->entityRepo->getRecentlyCreated('book', $count, 0, $createdByUserQuery),
235 'shelves' => $this->entityRepo->getRecentlyCreated('bookshelf', $count, 0, $createdByUserQuery)
240 * Get asset created counts for the give user.
241 * @param \BookStack\Auth\User $user
244 public function getAssetCounts(User $user)
247 'pages' => $this->entityRepo->getUserTotalCreated('page', $user),
248 'chapters' => $this->entityRepo->getUserTotalCreated('chapter', $user),
249 'books' => $this->entityRepo->getUserTotalCreated('book', $user),
250 'shelves' => $this->entityRepo->getUserTotalCreated('bookshelf', $user),
255 * Get the roles in the system that are assignable to a user.
258 public function getAllRoles()
260 return $this->role->newQuery()->orderBy('name', 'asc')->get();
264 * Get all the roles which can be given restricted access to
265 * other entities in the system.
268 public function getRestrictableRoles()
270 return $this->role->where('system_name', '!=', 'admin')->get();
274 * Get an avatar image for a user and set it as their avatar.
275 * Returns early if avatars disabled or not set in config.
279 public function downloadAndAssignUserAvatar(User $user)
281 if (!Images::avatarFetchEnabled()) {
286 $avatar = Images::saveUserAvatar($user);
287 $user->avatar()->associate($avatar);
290 } catch (Exception $e) {
291 \Log::error('Failed to save user avatar image');