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