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;
16 protected $entityRepo;
19 * UserRepo constructor.
22 * @param EntityRepo $entityRepo
24 public function __construct(User $user, Role $role, EntityRepo $entityRepo)
28 $this->entityRepo = $entityRepo;
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 \Illuminate\Database\Eloquent\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 \Illuminate\Database\Eloquent\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
83 * @return \BookStack\Auth\User
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.
123 * @param \BookStack\Auth\User $user
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
177 * @return \BookStack\Auth\User
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.
191 * @param \BookStack\Auth\User $user
194 public function destroy(User $user)
196 $user->socialAccounts()->delete();
199 // Delete user profile images
200 $profileImages = $images = Image::where('type', '=', 'user')->where('created_by', '=', $user->id)->get();
201 foreach ($profileImages as $image) {
202 Images::destroy($image);
207 * Get the latest activity for a user.
208 * @param \BookStack\Auth\User $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.
220 * @param \BookStack\Auth\User $user
224 public function getRecentlyCreated(User $user, $count = 20)
227 'pages' => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
228 $query->where('created_by', '=', $user->id);
230 'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
231 $query->where('created_by', '=', $user->id);
233 'books' => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
234 $query->where('created_by', '=', $user->id);
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),
254 * Get the roles in the system that are assignable to a user.
257 public function getAllRoles()
259 return $this->role->all();
263 * Get all the roles which can be given restricted access to
264 * other entities in the system.
267 public function getRestrictableRoles()
269 return $this->role->where('system_name', '!=', 'admin')->get();
273 * Get an avatar image for a user and set it as their avatar.
274 * Returns early if avatars disabled or not set in config.
278 public function downloadAndAssignUserAvatar(User $user)
280 if (!Images::avatarFetchEnabled()) {
285 $avatar = Images::saveUserAvatar($user);
286 $user->avatar()->associate($avatar);
289 } catch (Exception $e) {
290 \Log::error('Failed to save user avatar image');