]> BookStack Code Mirror - bookstack/blob - app/Users/UserRepo.php
d24f7002e710e678877263f1f3763222b29bc9ed
[bookstack] / app / Users / UserRepo.php
1 <?php
2
3 namespace BookStack\Users;
4
5 use BookStack\Access\UserInviteException;
6 use BookStack\Access\UserInviteService;
7 use BookStack\Activity\ActivityType;
8 use BookStack\Entities\EntityProvider;
9 use BookStack\Exceptions\NotifyException;
10 use BookStack\Exceptions\UserUpdateException;
11 use BookStack\Facades\Activity;
12 use BookStack\Uploads\UserAvatars;
13 use BookStack\Users\Models\Role;
14 use BookStack\Users\Models\User;
15 use Exception;
16 use Illuminate\Support\Facades\Hash;
17 use Illuminate\Support\Facades\Log;
18 use Illuminate\Support\Str;
19
20 class UserRepo
21 {
22     public function __construct(
23         protected UserAvatars $userAvatar,
24         protected UserInviteService $inviteService
25     ) {
26     }
27
28
29     /**
30      * Get a user by their email address.
31      */
32     public function getByEmail(string $email): ?User
33     {
34         return User::query()->where('email', '=', $email)->first();
35     }
36
37     /**
38      * Get a user by their ID.
39      */
40     public function getById(int $id): User
41     {
42         return User::query()->findOrFail($id);
43     }
44
45     /**
46      * Get a user by their slug.
47      */
48     public function getBySlug(string $slug): User
49     {
50         return User::query()->where('slug', '=', $slug)->firstOrFail();
51     }
52
53     /**
54      * Create a new basic instance of user with the given pre-validated data.
55      *
56      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
57      */
58     public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
59     {
60         $user = new User();
61         $user->name = $data['name'];
62         $user->email = $data['email'];
63         $user->password = Hash::make(empty($data['password']) ? Str::random(32) : $data['password']);
64         $user->email_confirmed = $emailConfirmed;
65         $user->external_auth_id = $data['external_auth_id'] ?? '';
66
67         $user->refreshSlug();
68         $user->save();
69
70         if (!empty($data['language'])) {
71             setting()->putUser($user, 'language', $data['language']);
72         }
73
74         if (isset($data['roles'])) {
75             $this->setUserRoles($user, $data['roles']);
76         }
77
78         $this->downloadAndAssignUserAvatar($user);
79
80         return $user;
81     }
82
83     /**
84      * As per "createWithoutActivity" but records a "create" activity.
85      *
86      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
87      * @throws UserInviteException
88      */
89     public function create(array $data, bool $sendInvite = false): User
90     {
91         $user = $this->createWithoutActivity($data, true);
92
93         if ($sendInvite) {
94             $this->inviteService->sendInvitation($user);
95         }
96
97         Activity::add(ActivityType::USER_CREATE, $user);
98
99         return $user;
100     }
101
102     /**
103      * Update the given user with the given data, but do not create an activity.
104      *
105      * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
106      *
107      * @throws UserUpdateException
108      */
109     public function updateWithoutActivity(User $user, array $data, bool $manageUsersAllowed): User
110     {
111         if (!empty($data['name'])) {
112             $user->name = $data['name'];
113             $user->refreshSlug();
114         }
115
116         if (!empty($data['email']) && $manageUsersAllowed) {
117             $user->email = $data['email'];
118         }
119
120         if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
121             $user->external_auth_id = $data['external_auth_id'];
122         }
123
124         if (isset($data['roles']) && $manageUsersAllowed) {
125             $this->setUserRoles($user, $data['roles']);
126         }
127
128         if (!empty($data['password'])) {
129             $user->password = Hash::make($data['password']);
130         }
131
132         if (!empty($data['language'])) {
133             setting()->putUser($user, 'language', $data['language']);
134         }
135
136         $user->save();
137
138         return $user;
139     }
140
141     /**
142      * Update the given user with the given data.
143      *
144      * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
145      *
146      * @throws UserUpdateException
147      */
148     public function update(User $user, array $data, bool $manageUsersAllowed): User
149     {
150         $user = $this->updateWithoutActivity($user, $data, $manageUsersAllowed);
151
152         Activity::add(ActivityType::USER_UPDATE, $user);
153
154         return $user;
155     }
156
157     /**
158      * Remove the given user from storage, Delete all related content.
159      *
160      * @throws Exception
161      */
162     public function destroy(User $user, ?int $newOwnerId = null)
163     {
164         $this->ensureDeletable($user);
165
166         $user->socialAccounts()->delete();
167         $user->apiTokens()->delete();
168         $user->favourites()->delete();
169         $user->mfaValues()->delete();
170         $user->watches()->delete();
171         $user->delete();
172
173         // Delete user profile images
174         $this->userAvatar->destroyAllForUser($user);
175
176         // Delete related activities
177         setting()->deleteUserSettings($user->id);
178
179         if (!empty($newOwnerId)) {
180             $newOwner = User::query()->find($newOwnerId);
181             if (!is_null($newOwner)) {
182                 $this->migrateOwnership($user, $newOwner);
183             }
184         }
185
186         Activity::add(ActivityType::USER_DELETE, $user);
187     }
188
189     /**
190      * @throws NotifyException
191      */
192     protected function ensureDeletable(User $user): void
193     {
194         if ($this->isOnlyAdmin($user)) {
195             throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
196         }
197
198         if ($user->system_name === 'public') {
199             throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
200         }
201     }
202
203     /**
204      * Migrate ownership of items in the system from one user to another.
205      */
206     protected function migrateOwnership(User $fromUser, User $toUser)
207     {
208         $entities = (new EntityProvider())->all();
209         foreach ($entities as $instance) {
210             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
211                 ->update(['owned_by' => $toUser->id]);
212         }
213     }
214
215     /**
216      * Get an avatar image for a user and set it as their avatar.
217      * Returns early if avatars disabled or not set in config.
218      */
219     protected function downloadAndAssignUserAvatar(User $user): void
220     {
221         try {
222             $this->userAvatar->fetchAndAssignToUser($user);
223         } catch (Exception $e) {
224             Log::error('Failed to save user avatar image');
225         }
226     }
227
228     /**
229      * Checks if the give user is the only admin.
230      */
231     protected function isOnlyAdmin(User $user): bool
232     {
233         if (!$user->hasSystemRole('admin')) {
234             return false;
235         }
236
237         $adminRole = Role::getSystemRole('admin');
238         if ($adminRole->users()->count() > 1) {
239             return false;
240         }
241
242         return true;
243     }
244
245     /**
246      * Set the assigned user roles via an array of role IDs.
247      *
248      * @throws UserUpdateException
249      */
250     protected function setUserRoles(User $user, array $roles)
251     {
252         $roles = array_filter(array_values($roles));
253
254         if ($this->demotingLastAdmin($user, $roles)) {
255             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
256         }
257
258         $user->roles()->sync($roles);
259     }
260
261     /**
262      * Check if the given user is the last admin and their new roles no longer
263      * contains the admin role.
264      */
265     protected function demotingLastAdmin(User $user, array $newRoles): bool
266     {
267         if ($this->isOnlyAdmin($user)) {
268             $adminRole = Role::getSystemRole('admin');
269             if (!in_array(strval($adminRole->id), $newRoles)) {
270                 return true;
271             }
272         }
273
274         return false;
275     }
276 }