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