]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Applied latest styleci changes
[bookstack] / app / Auth / UserRepo.php
1 <?php
2
3 namespace BookStack\Auth;
4
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Exceptions\NotFoundException;
11 use BookStack\Exceptions\UserUpdateException;
12 use BookStack\Uploads\UserAvatars;
13 use Exception;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Eloquent\Collection;
16 use Illuminate\Pagination\LengthAwarePaginator;
17 use Illuminate\Support\Facades\Log;
18
19 class UserRepo
20 {
21     protected $userAvatar;
22
23     /**
24      * UserRepo constructor.
25      */
26     public function __construct(UserAvatars $userAvatar)
27     {
28         $this->userAvatar = $userAvatar;
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      * Get all the users with their permissions.
57      */
58     public function getAllUsers(): Collection
59     {
60         return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
61     }
62
63     /**
64      * Get all the users with their permissions in a paginated format.
65      * Note: Due to the use of email search this should only be used when
66      * user is assumed to be trusted. (Admin users).
67      * Email search can be abused to extract email addresses.
68      */
69     public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
70     {
71         $sort = $sortData['sort'];
72
73         $query = User::query()->select(['*'])
74             ->scopes(['withLastActivityAt'])
75             ->with(['roles', 'avatar'])
76             ->withCount('mfaValues')
77             ->orderBy($sort, $sortData['order']);
78
79         if ($sortData['search']) {
80             $term = '%' . $sortData['search'] . '%';
81             $query->where(function ($query) use ($term) {
82                 $query->where('name', 'like', $term)
83                     ->orWhere('email', 'like', $term);
84             });
85         }
86
87         return $query->paginate($count);
88     }
89
90     /**
91      * Creates a new user and attaches a role to them.
92      */
93     public function registerNew(array $data, bool $emailConfirmed = false): User
94     {
95         $user = $this->create($data, $emailConfirmed);
96         $user->attachDefaultRole();
97         $this->downloadAndAssignUserAvatar($user);
98
99         return $user;
100     }
101
102     /**
103      * Assign a user to a system-level role.
104      *
105      * @throws NotFoundException
106      */
107     public function attachSystemRole(User $user, string $systemRoleName)
108     {
109         $role = Role::getSystemRole($systemRoleName);
110         if (is_null($role)) {
111             throw new NotFoundException("Role '{$systemRoleName}' not found");
112         }
113         $user->attachRole($role);
114     }
115
116     /**
117      * Checks if the give user is the only admin.
118      */
119     public function isOnlyAdmin(User $user): bool
120     {
121         if (!$user->hasSystemRole('admin')) {
122             return false;
123         }
124
125         $adminRole = Role::getSystemRole('admin');
126         if ($adminRole->users()->count() > 1) {
127             return false;
128         }
129
130         return true;
131     }
132
133     /**
134      * Set the assigned user roles via an array of role IDs.
135      *
136      * @throws UserUpdateException
137      */
138     public function setUserRoles(User $user, array $roles)
139     {
140         if ($this->demotingLastAdmin($user, $roles)) {
141             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
142         }
143
144         $user->roles()->sync($roles);
145     }
146
147     /**
148      * Check if the given user is the last admin and their new roles no longer
149      * contains the admin role.
150      */
151     protected function demotingLastAdmin(User $user, array $newRoles): bool
152     {
153         if ($this->isOnlyAdmin($user)) {
154             $adminRole = Role::getSystemRole('admin');
155             if (!in_array(strval($adminRole->id), $newRoles)) {
156                 return true;
157             }
158         }
159
160         return false;
161     }
162
163     /**
164      * Create a new basic instance of user.
165      */
166     public function create(array $data, bool $emailConfirmed = false): User
167     {
168         $details = [
169             'name'             => $data['name'],
170             'email'            => $data['email'],
171             'password'         => bcrypt($data['password']),
172             'email_confirmed'  => $emailConfirmed,
173             'external_auth_id' => $data['external_auth_id'] ?? '',
174         ];
175
176         $user = new User();
177         $user->forceFill($details);
178         $user->refreshSlug();
179         $user->save();
180
181         return $user;
182     }
183
184     /**
185      * Remove the given user from storage, Delete all related content.
186      *
187      * @throws Exception
188      */
189     public function destroy(User $user, ?int $newOwnerId = null)
190     {
191         $user->socialAccounts()->delete();
192         $user->apiTokens()->delete();
193         $user->favourites()->delete();
194         $user->mfaValues()->delete();
195         $user->delete();
196
197         // Delete user profile images
198         $this->userAvatar->destroyAllForUser($user);
199
200         if (!empty($newOwnerId)) {
201             $newOwner = User::query()->find($newOwnerId);
202             if (!is_null($newOwner)) {
203                 $this->migrateOwnership($user, $newOwner);
204             }
205         }
206     }
207
208     /**
209      * Migrate ownership of items in the system from one user to another.
210      */
211     protected function migrateOwnership(User $fromUser, User $toUser)
212     {
213         $entities = (new EntityProvider())->all();
214         foreach ($entities as $instance) {
215             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
216                 ->update(['owned_by' => $toUser->id]);
217         }
218     }
219
220     /**
221      * Get the recently created content for this given user.
222      */
223     public function getRecentlyCreated(User $user, int $count = 20): array
224     {
225         $query = function (Builder $query) use ($user, $count) {
226             return $query->orderBy('created_at', 'desc')
227                 ->where('created_by', '=', $user->id)
228                 ->take($count)
229                 ->get();
230         };
231
232         return [
233             'pages'    => $query(Page::visible()->where('draft', '=', false)),
234             'chapters' => $query(Chapter::visible()),
235             'books'    => $query(Book::visible()),
236             'shelves'  => $query(Bookshelf::visible()),
237         ];
238     }
239
240     /**
241      * Get asset created counts for the give user.
242      */
243     public function getAssetCounts(User $user): array
244     {
245         $createdBy = ['created_by' => $user->id];
246
247         return [
248             'pages'       => Page::visible()->where($createdBy)->count(),
249             'chapters'    => Chapter::visible()->where($createdBy)->count(),
250             'books'       => Book::visible()->where($createdBy)->count(),
251             'shelves'     => Bookshelf::visible()->where($createdBy)->count(),
252         ];
253     }
254
255     /**
256      * Get the roles in the system that are assignable to a user.
257      */
258     public function getAllRoles(): Collection
259     {
260         return Role::query()->orderBy('display_name', 'asc')->get();
261     }
262
263     /**
264      * Get an avatar image for a user and set it as their avatar.
265      * Returns early if avatars disabled or not set in config.
266      */
267     public function downloadAndAssignUserAvatar(User $user): void
268     {
269         try {
270             $this->userAvatar->fetchAndAssignToUser($user);
271         } catch (Exception $e) {
272             Log::error('Failed to save user avatar image');
273         }
274     }
275 }