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