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