]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Added check for last admin on role change
[bookstack] / app / Auth / UserRepo.php
1 <?php namespace BookStack\Auth;
2
3 use Activity;
4 use BookStack\Entities\Repos\EntityRepo;
5 use BookStack\Exceptions\NotFoundException;
6 use BookStack\Exceptions\UserUpdateException;
7 use BookStack\Uploads\Image;
8 use Exception;
9 use Images;
10
11 class UserRepo
12 {
13
14     protected $user;
15     protected $role;
16     protected $entityRepo;
17
18     /**
19      * UserRepo constructor.
20      * @param User $user
21      * @param Role $role
22      * @param EntityRepo $entityRepo
23      */
24     public function __construct(User $user, Role $role, EntityRepo $entityRepo)
25     {
26         $this->user = $user;
27         $this->role = $role;
28         $this->entityRepo = $entityRepo;
29     }
30
31     /**
32      * @param string $email
33      * @return User|null
34      */
35     public function getByEmail($email)
36     {
37         return $this->user->where('email', '=', $email)->first();
38     }
39
40     /**
41      * @param int $id
42      * @return User
43      */
44     public function getById($id)
45     {
46         return $this->user->newQuery()->findOrFail($id);
47     }
48
49     /**
50      * Get all the users with their permissions.
51      * @return \Illuminate\Database\Eloquent\Builder|static
52      */
53     public function getAllUsers()
54     {
55         return $this->user->with('roles', 'avatar')->orderBy('name', 'asc')->get();
56     }
57
58     /**
59      * Get all the users with their permissions in a paginated format.
60      * @param int $count
61      * @param $sortData
62      * @return \Illuminate\Database\Eloquent\Builder|static
63      */
64     public function getAllUsersPaginatedAndSorted($count, $sortData)
65     {
66         $query = $this->user->with('roles', 'avatar')->orderBy($sortData['sort'], $sortData['order']);
67
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);
73             });
74         }
75
76         return $query->paginate($count);
77     }
78
79      /**
80      * Creates a new user and attaches a role to them.
81      * @param array $data
82      * @param boolean $verifyEmail
83      * @return \BookStack\Auth\User
84      */
85     public function registerNew(array $data, $verifyEmail = false)
86     {
87         $user = $this->create($data, $verifyEmail);
88         $this->attachDefaultRole($user);
89         $this->downloadAndAssignUserAvatar($user);
90
91         return $user;
92     }
93
94     /**
95      * Give a user the default role. Used when creating a new user.
96      * @param User $user
97      */
98     public function attachDefaultRole(User $user)
99     {
100         $roleId = setting('registration-role');
101         if ($roleId !== false && $user->roles()->where('id', '=', $roleId)->count() === 0) {
102             $user->attachRoleId($roleId);
103         }
104     }
105
106     /**
107      * Assign a user to a system-level role.
108      * @param User $user
109      * @param $systemRoleName
110      * @throws NotFoundException
111      */
112     public function attachSystemRole(User $user, $systemRoleName)
113     {
114         $role = $this->role->newQuery()->where('system_name', '=', $systemRoleName)->first();
115         if ($role === null) {
116             throw new NotFoundException("Role '{$systemRoleName}' not found");
117         }
118         $user->attachRole($role);
119     }
120
121     /**
122      * Checks if the give user is the only admin.
123      * @param \BookStack\Auth\User $user
124      * @return bool
125      */
126     public function isOnlyAdmin(User $user)
127     {
128         if (!$user->hasSystemRole('admin')) {
129             return false;
130         }
131
132         $adminRole = $this->role->getSystemRole('admin');
133         if ($adminRole->users->count() > 1) {
134             return false;
135         }
136         return true;
137     }
138
139     /**
140      * Set the assigned user roles via an array of role IDs.
141      * @param User $user
142      * @param array $roles
143      * @throws UserUpdateException
144      */
145     public function setUserRoles(User $user, array $roles)
146     {
147         if ($this->demotingLastAdmin($user, $roles)) {
148             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
149         }
150
151         $user->roles()->sync($roles);
152     }
153
154     /**
155      * Check if the given user is the last admin and their new roles no longer
156      * contains the admin role.
157      * @param User $user
158      * @param array $newRoles
159      * @return bool
160      */
161     protected function demotingLastAdmin(User $user, array $newRoles) : bool
162     {
163         if ($this->isOnlyAdmin($user)) {
164             $adminRole = $this->role->getSystemRole('admin');
165             if (!in_array(strval($adminRole->id), $newRoles)) {
166                 return true;
167             }
168         }
169
170         return false;
171     }
172
173     /**
174      * Create a new basic instance of user.
175      * @param array $data
176      * @param boolean $verifyEmail
177      * @return \BookStack\Auth\User
178      */
179     public function create(array $data, $verifyEmail = false)
180     {
181         return $this->user->forceCreate([
182             'name'     => $data['name'],
183             'email'    => $data['email'],
184             'password' => bcrypt($data['password']),
185             'email_confirmed' => $verifyEmail
186         ]);
187     }
188
189     /**
190      * Remove the given user from storage, Delete all related content.
191      * @param \BookStack\Auth\User $user
192      * @throws Exception
193      */
194     public function destroy(User $user)
195     {
196         $user->socialAccounts()->delete();
197         $user->delete();
198         
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);
203         }
204     }
205
206     /**
207      * Get the latest activity for a user.
208      * @param \BookStack\Auth\User $user
209      * @param int $count
210      * @param int $page
211      * @return array
212      */
213     public function getActivity(User $user, $count = 20, $page = 0)
214     {
215         return Activity::userActivity($user, $count, $page);
216     }
217
218     /**
219      * Get the recently created content for this given user.
220      * @param \BookStack\Auth\User $user
221      * @param int $count
222      * @return mixed
223      */
224     public function getRecentlyCreated(User $user, $count = 20)
225     {
226         return [
227             'pages'    => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
228                 $query->where('created_by', '=', $user->id);
229             }),
230             'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
231                 $query->where('created_by', '=', $user->id);
232             }),
233             'books'    => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
234                 $query->where('created_by', '=', $user->id);
235             })
236         ];
237     }
238
239     /**
240      * Get asset created counts for the give user.
241      * @param \BookStack\Auth\User $user
242      * @return array
243      */
244     public function getAssetCounts(User $user)
245     {
246         return [
247             'pages'    => $this->entityRepo->getUserTotalCreated('page', $user),
248             'chapters' => $this->entityRepo->getUserTotalCreated('chapter', $user),
249             'books'    => $this->entityRepo->getUserTotalCreated('book', $user),
250         ];
251     }
252
253     /**
254      * Get the roles in the system that are assignable to a user.
255      * @return mixed
256      */
257     public function getAllRoles()
258     {
259         return $this->role->all();
260     }
261
262     /**
263      * Get all the roles which can be given restricted access to
264      * other entities in the system.
265      * @return mixed
266      */
267     public function getRestrictableRoles()
268     {
269         return $this->role->where('system_name', '!=', 'admin')->get();
270     }
271
272     /**
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.
275      * @param User $user
276      * @return bool
277      */
278     public function downloadAndAssignUserAvatar(User $user)
279     {
280         if (!Images::avatarFetchEnabled()) {
281             return false;
282         }
283
284         try {
285             $avatar = Images::saveUserAvatar($user);
286             $user->avatar()->associate($avatar);
287             $user->save();
288             return true;
289         } catch (Exception $e) {
290             \Log::error('Failed to save user avatar image');
291             return false;
292         }
293     }
294 }