]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Revamped workings of WYSIWYG code blocks
[bookstack] / app / Auth / UserRepo.php
1 <?php
2
3 namespace BookStack\Auth;
4
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\Access\UserInviteService;
7 use BookStack\Entities\EntityProvider;
8 use BookStack\Entities\Models\Book;
9 use BookStack\Entities\Models\Bookshelf;
10 use BookStack\Entities\Models\Chapter;
11 use BookStack\Entities\Models\Page;
12 use BookStack\Exceptions\NotFoundException;
13 use BookStack\Exceptions\NotifyException;
14 use BookStack\Exceptions\UserUpdateException;
15 use BookStack\Facades\Activity;
16 use BookStack\Uploads\UserAvatars;
17 use Exception;
18 use Illuminate\Database\Eloquent\Builder;
19 use Illuminate\Database\Eloquent\Collection;
20 use Illuminate\Pagination\LengthAwarePaginator;
21 use Illuminate\Support\Facades\Log;
22 use Illuminate\Support\Str;
23
24 class UserRepo
25 {
26     protected $userAvatar;
27     protected $inviteService;
28
29     /**
30      * UserRepo constructor.
31      */
32     public function __construct(UserAvatars $userAvatar, UserInviteService $inviteService)
33     {
34         $this->userAvatar = $userAvatar;
35         $this->inviteService = $inviteService;
36     }
37
38     /**
39      * Get a user by their email address.
40      */
41     public function getByEmail(string $email): ?User
42     {
43         return User::query()->where('email', '=', $email)->first();
44     }
45
46     /**
47      * Get a user by their ID.
48      */
49     public function getById(int $id): User
50     {
51         return User::query()->findOrFail($id);
52     }
53
54     /**
55      * Get a user by their slug.
56      */
57     public function getBySlug(string $slug): User
58     {
59         return User::query()->where('slug', '=', $slug)->firstOrFail();
60     }
61
62     /**
63      * Get all users as Builder for API.
64      */
65     public function getApiUsersBuilder(): Builder
66     {
67         return User::query()->select(['*'])
68             ->scopes('withLastActivityAt')
69             ->with(['avatar']);
70     }
71
72     /**
73      * Get all the users with their permissions in a paginated format.
74      * Note: Due to the use of email search this should only be used when
75      * user is assumed to be trusted. (Admin users).
76      * Email search can be abused to extract email addresses.
77      */
78     public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
79     {
80         $sort = $sortData['sort'];
81
82         $query = User::query()->select(['*'])
83             ->scopes(['withLastActivityAt'])
84             ->with(['roles', 'avatar'])
85             ->withCount('mfaValues')
86             ->orderBy($sort, $sortData['order']);
87
88         if ($sortData['search']) {
89             $term = '%' . $sortData['search'] . '%';
90             $query->where(function ($query) use ($term) {
91                 $query->where('name', 'like', $term)
92                     ->orWhere('email', 'like', $term);
93             });
94         }
95
96         return $query->paginate($count);
97     }
98
99     /**
100      * Assign a user to a system-level role.
101      *
102      * @throws NotFoundException
103      */
104     public function attachSystemRole(User $user, string $systemRoleName)
105     {
106         $role = Role::getSystemRole($systemRoleName);
107         if (is_null($role)) {
108             throw new NotFoundException("Role '{$systemRoleName}' not found");
109         }
110         $user->attachRole($role);
111     }
112
113     /**
114      * Checks if the give user is the only admin.
115      */
116     public function isOnlyAdmin(User $user): bool
117     {
118         if (!$user->hasSystemRole('admin')) {
119             return false;
120         }
121
122         $adminRole = Role::getSystemRole('admin');
123         if ($adminRole->users()->count() > 1) {
124             return false;
125         }
126
127         return true;
128     }
129
130     /**
131      * Set the assigned user roles via an array of role IDs.
132      *
133      * @throws UserUpdateException
134      */
135     public function setUserRoles(User $user, array $roles)
136     {
137         if ($this->demotingLastAdmin($user, $roles)) {
138             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
139         }
140
141         $user->roles()->sync($roles);
142     }
143
144     /**
145      * Check if the given user is the last admin and their new roles no longer
146      * contains the admin role.
147      */
148     protected function demotingLastAdmin(User $user, array $newRoles): bool
149     {
150         if ($this->isOnlyAdmin($user)) {
151             $adminRole = Role::getSystemRole('admin');
152             if (!in_array(strval($adminRole->id), $newRoles)) {
153                 return true;
154             }
155         }
156
157         return false;
158     }
159
160     /**
161      * Create a new basic instance of user with the given pre-validated data.
162      *
163      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
164      */
165     public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
166     {
167         $user = new User();
168         $user->name = $data['name'];
169         $user->email = $data['email'];
170         $user->password = bcrypt(empty($data['password']) ? Str::random(32) : $data['password']);
171         $user->email_confirmed = $emailConfirmed;
172         $user->external_auth_id = $data['external_auth_id'] ?? '';
173
174         $user->refreshSlug();
175         $user->save();
176
177         if (!empty($data['language'])) {
178             setting()->putUser($user, 'language', $data['language']);
179         }
180
181         if (isset($data['roles'])) {
182             $this->setUserRoles($user, $data['roles']);
183         }
184
185         $this->downloadAndAssignUserAvatar($user);
186
187         return $user;
188     }
189
190     /**
191      * As per "createWithoutActivity" but records a "create" activity.
192      *
193      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
194      */
195     public function create(array $data, bool $sendInvite = false): User
196     {
197         $user = $this->createWithoutActivity($data, true);
198
199         if ($sendInvite) {
200             $this->inviteService->sendInvitation($user);
201         }
202
203         Activity::add(ActivityType::USER_CREATE, $user);
204
205         return $user;
206     }
207
208     /**
209      * Update the given user with the given data.
210      *
211      * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
212      *
213      * @throws UserUpdateException
214      */
215     public function update(User $user, array $data, bool $manageUsersAllowed): User
216     {
217         if (!empty($data['name'])) {
218             $user->name = $data['name'];
219             $user->refreshSlug();
220         }
221
222         if (!empty($data['email']) && $manageUsersAllowed) {
223             $user->email = $data['email'];
224         }
225
226         if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
227             $user->external_auth_id = $data['external_auth_id'];
228         }
229
230         if (isset($data['roles']) && $manageUsersAllowed) {
231             $this->setUserRoles($user, $data['roles']);
232         }
233
234         if (!empty($data['password'])) {
235             $user->password = bcrypt($data['password']);
236         }
237
238         if (!empty($data['language'])) {
239             setting()->putUser($user, 'language', $data['language']);
240         }
241
242         $user->save();
243         Activity::add(ActivityType::USER_UPDATE, $user);
244
245         return $user;
246     }
247
248     /**
249      * Remove the given user from storage, Delete all related content.
250      *
251      * @throws Exception
252      */
253     public function destroy(User $user, ?int $newOwnerId = null)
254     {
255         $this->ensureDeletable($user);
256
257         $user->socialAccounts()->delete();
258         $user->apiTokens()->delete();
259         $user->favourites()->delete();
260         $user->mfaValues()->delete();
261         $user->delete();
262
263         // Delete user profile images
264         $this->userAvatar->destroyAllForUser($user);
265
266         if (!empty($newOwnerId)) {
267             $newOwner = User::query()->find($newOwnerId);
268             if (!is_null($newOwner)) {
269                 $this->migrateOwnership($user, $newOwner);
270             }
271         }
272
273         Activity::add(ActivityType::USER_DELETE, $user);
274     }
275
276     /**
277      * @throws NotifyException
278      */
279     protected function ensureDeletable(User $user): void
280     {
281         if ($this->isOnlyAdmin($user)) {
282             throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
283         }
284
285         if ($user->system_name === 'public') {
286             throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
287         }
288     }
289
290     /**
291      * Migrate ownership of items in the system from one user to another.
292      */
293     protected function migrateOwnership(User $fromUser, User $toUser)
294     {
295         $entities = (new EntityProvider())->all();
296         foreach ($entities as $instance) {
297             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
298                 ->update(['owned_by' => $toUser->id]);
299         }
300     }
301
302     /**
303      * Get the recently created content for this given user.
304      */
305     public function getRecentlyCreated(User $user, int $count = 20): array
306     {
307         $query = function (Builder $query) use ($user, $count) {
308             return $query->orderBy('created_at', 'desc')
309                 ->where('created_by', '=', $user->id)
310                 ->take($count)
311                 ->get();
312         };
313
314         return [
315             'pages'    => $query(Page::visible()->where('draft', '=', false)),
316             'chapters' => $query(Chapter::visible()),
317             'books'    => $query(Book::visible()),
318             'shelves'  => $query(Bookshelf::visible()),
319         ];
320     }
321
322     /**
323      * Get asset created counts for the give user.
324      */
325     public function getAssetCounts(User $user): array
326     {
327         $createdBy = ['created_by' => $user->id];
328
329         return [
330             'pages'    => Page::visible()->where($createdBy)->count(),
331             'chapters' => Chapter::visible()->where($createdBy)->count(),
332             'books'    => Book::visible()->where($createdBy)->count(),
333             'shelves'  => Bookshelf::visible()->where($createdBy)->count(),
334         ];
335     }
336
337     /**
338      * Get the roles in the system that are assignable to a user.
339      */
340     public function getAllRoles(): Collection
341     {
342         return Role::query()->orderBy('display_name', 'asc')->get();
343     }
344
345     /**
346      * Get an avatar image for a user and set it as their avatar.
347      * Returns early if avatars disabled or not set in config.
348      */
349     public function downloadAndAssignUserAvatar(User $user): void
350     {
351         try {
352             $this->userAvatar->fetchAndAssignToUser($user);
353         } catch (Exception $e) {
354             Log::error('Failed to save user avatar image');
355         }
356     }
357 }