]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Merge branch 'tinymce' into development
[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      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
163      */
164     public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
165     {
166         $user = new User();
167         $user->name = $data['name'];
168         $user->email = $data['email'];
169         $user->password = bcrypt(empty($data['password']) ? Str::random(32) : $data['password']);
170         $user->email_confirmed = $emailConfirmed;
171         $user->external_auth_id = $data['external_auth_id'] ?? '';
172
173         $user->refreshSlug();
174         $user->save();
175
176         if (!empty($data['language'])) {
177             setting()->putUser($user, 'language', $data['language']);
178         }
179
180         if (isset($data['roles'])) {
181             $this->setUserRoles($user, $data['roles']);
182         }
183
184         $this->downloadAndAssignUserAvatar($user);
185
186         return $user;
187     }
188
189     /**
190      * As per "createWithoutActivity" but records a "create" activity.
191      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
192      */
193     public function create(array $data, bool $sendInvite = false): User
194     {
195         $user = $this->createWithoutActivity($data, true);
196
197         if ($sendInvite) {
198             $this->inviteService->sendInvitation($user);
199         }
200
201         Activity::add(ActivityType::USER_CREATE, $user);
202         return $user;
203     }
204
205     /**
206      * Update the given user with the given data.
207      * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
208      * @throws UserUpdateException
209      */
210     public function update(User $user, array $data, bool $manageUsersAllowed): User
211     {
212         if (!empty($data['name'])) {
213             $user->name = $data['name'];
214             $user->refreshSlug();
215         }
216
217         if (!empty($data['email']) && $manageUsersAllowed) {
218             $user->email = $data['email'];
219         }
220
221         if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
222             $user->external_auth_id = $data['external_auth_id'];
223         }
224
225         if (isset($data['roles']) && $manageUsersAllowed) {
226             $this->setUserRoles($user, $data['roles']);
227         }
228
229         if (!empty($data['password'])) {
230             $user->password = bcrypt($data['password']);
231         }
232
233         if (!empty($data['language'])) {
234             setting()->putUser($user, 'language', $data['language']);
235         }
236
237         $user->save();
238         Activity::add(ActivityType::USER_UPDATE, $user);
239
240         return $user;
241     }
242
243     /**
244      * Remove the given user from storage, Delete all related content.
245      *
246      * @throws Exception
247      */
248     public function destroy(User $user, ?int $newOwnerId = null)
249     {
250         $this->ensureDeletable($user);
251
252         $user->socialAccounts()->delete();
253         $user->apiTokens()->delete();
254         $user->favourites()->delete();
255         $user->mfaValues()->delete();
256         $user->delete();
257
258         // Delete user profile images
259         $this->userAvatar->destroyAllForUser($user);
260
261         if (!empty($newOwnerId)) {
262             $newOwner = User::query()->find($newOwnerId);
263             if (!is_null($newOwner)) {
264                 $this->migrateOwnership($user, $newOwner);
265             }
266         }
267
268         Activity::add(ActivityType::USER_DELETE, $user);
269     }
270
271     /**
272      * @throws NotifyException
273      */
274     protected function ensureDeletable(User $user): void
275     {
276         if ($this->isOnlyAdmin($user)) {
277             throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
278         }
279
280         if ($user->system_name === 'public') {
281             throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
282         }
283     }
284
285     /**
286      * Migrate ownership of items in the system from one user to another.
287      */
288     protected function migrateOwnership(User $fromUser, User $toUser)
289     {
290         $entities = (new EntityProvider())->all();
291         foreach ($entities as $instance) {
292             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
293                 ->update(['owned_by' => $toUser->id]);
294         }
295     }
296
297     /**
298      * Get the recently created content for this given user.
299      */
300     public function getRecentlyCreated(User $user, int $count = 20): array
301     {
302         $query = function (Builder $query) use ($user, $count) {
303             return $query->orderBy('created_at', 'desc')
304                 ->where('created_by', '=', $user->id)
305                 ->take($count)
306                 ->get();
307         };
308
309         return [
310             'pages' => $query(Page::visible()->where('draft', '=', false)),
311             'chapters' => $query(Chapter::visible()),
312             'books' => $query(Book::visible()),
313             'shelves' => $query(Bookshelf::visible()),
314         ];
315     }
316
317     /**
318      * Get asset created counts for the give user.
319      */
320     public function getAssetCounts(User $user): array
321     {
322         $createdBy = ['created_by' => $user->id];
323
324         return [
325             'pages' => Page::visible()->where($createdBy)->count(),
326             'chapters' => Chapter::visible()->where($createdBy)->count(),
327             'books' => Book::visible()->where($createdBy)->count(),
328             'shelves' => Bookshelf::visible()->where($createdBy)->count(),
329         ];
330     }
331
332     /**
333      * Get the roles in the system that are assignable to a user.
334      */
335     public function getAllRoles(): Collection
336     {
337         return Role::query()->orderBy('display_name', 'asc')->get();
338     }
339
340     /**
341      * Get an avatar image for a user and set it as their avatar.
342      * Returns early if avatars disabled or not set in config.
343      */
344     public function downloadAndAssignUserAvatar(User $user): void
345     {
346         try {
347             $this->userAvatar->fetchAndAssignToUser($user);
348         } catch (Exception $e) {
349             Log::error('Failed to save user avatar image');
350         }
351     }
352 }