]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Added configurable API throttling, Handled API errors standardly
[bookstack] / app / Auth / UserRepo.php
1 <?php namespace BookStack\Auth;
2
3 use Activity;
4 use BookStack\Entities\Book;
5 use BookStack\Entities\Bookshelf;
6 use BookStack\Entities\Chapter;
7 use BookStack\Entities\Page;
8 use BookStack\Exceptions\NotFoundException;
9 use BookStack\Exceptions\UserUpdateException;
10 use BookStack\Uploads\Image;
11 use Exception;
12 use Illuminate\Database\Eloquent\Builder;
13 use Images;
14 use Log;
15
16 class UserRepo
17 {
18
19     protected $user;
20     protected $role;
21
22     /**
23      * UserRepo constructor.
24      */
25     public function __construct(User $user, Role $role)
26     {
27         $this->user = $user;
28         $this->role = $role;
29     }
30
31     /**
32      * @param string $email
33      * @return User|null
34      */
35     public function getByEmail($email)
36     {
37         return $this->user->where('email', '=', $email)->first();
38     }
39
40     /**
41      * @param int $id
42      * @return User
43      */
44     public function getById($id)
45     {
46         return $this->user->newQuery()->findOrFail($id);
47     }
48
49     /**
50      * Get all the users with their permissions.
51      * @return Builder|static
52      */
53     public function getAllUsers()
54     {
55         return $this->user->with('roles', 'avatar')->orderBy('name', 'asc')->get();
56     }
57
58     /**
59      * Get all the users with their permissions in a paginated format.
60      * @param int $count
61      * @param $sortData
62      * @return Builder|static
63      */
64     public function getAllUsersPaginatedAndSorted($count, $sortData)
65     {
66         $query = $this->user->with('roles', 'avatar')->orderBy($sortData['sort'], $sortData['order']);
67
68         if ($sortData['search']) {
69             $term = '%' . $sortData['search'] . '%';
70             $query->where(function ($query) use ($term) {
71                 $query->where('name', 'like', $term)
72                     ->orWhere('email', 'like', $term);
73             });
74         }
75
76         return $query->paginate($count);
77     }
78
79      /**
80      * Creates a new user and attaches a role to them.
81      * @param array $data
82      * @param boolean $verifyEmail
83      * @return User
84      */
85     public function registerNew(array $data, $verifyEmail = false)
86     {
87         $user = $this->create($data, $verifyEmail);
88         $this->attachDefaultRole($user);
89         $this->downloadAndAssignUserAvatar($user);
90
91         return $user;
92     }
93
94     /**
95      * Give a user the default role. Used when creating a new user.
96      * @param User $user
97      */
98     public function attachDefaultRole(User $user)
99     {
100         $roleId = setting('registration-role');
101         if ($roleId !== false && $user->roles()->where('id', '=', $roleId)->count() === 0) {
102             $user->attachRoleId($roleId);
103         }
104     }
105
106     /**
107      * Assign a user to a system-level role.
108      * @param User $user
109      * @param $systemRoleName
110      * @throws NotFoundException
111      */
112     public function attachSystemRole(User $user, $systemRoleName)
113     {
114         $role = $this->role->newQuery()->where('system_name', '=', $systemRoleName)->first();
115         if ($role === null) {
116             throw new NotFoundException("Role '{$systemRoleName}' not found");
117         }
118         $user->attachRole($role);
119     }
120
121     /**
122      * Checks if the give user is the only admin.
123      * @param User $user
124      * @return bool
125      */
126     public function isOnlyAdmin(User $user)
127     {
128         if (!$user->hasSystemRole('admin')) {
129             return false;
130         }
131
132         $adminRole = $this->role->getSystemRole('admin');
133         if ($adminRole->users->count() > 1) {
134             return false;
135         }
136         return true;
137     }
138
139     /**
140      * Set the assigned user roles via an array of role IDs.
141      * @param User $user
142      * @param array $roles
143      * @throws UserUpdateException
144      */
145     public function setUserRoles(User $user, array $roles)
146     {
147         if ($this->demotingLastAdmin($user, $roles)) {
148             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
149         }
150
151         $user->roles()->sync($roles);
152     }
153
154     /**
155      * Check if the given user is the last admin and their new roles no longer
156      * contains the admin role.
157      * @param User $user
158      * @param array $newRoles
159      * @return bool
160      */
161     protected function demotingLastAdmin(User $user, array $newRoles) : bool
162     {
163         if ($this->isOnlyAdmin($user)) {
164             $adminRole = $this->role->getSystemRole('admin');
165             if (!in_array(strval($adminRole->id), $newRoles)) {
166                 return true;
167             }
168         }
169
170         return false;
171     }
172
173     /**
174      * Create a new basic instance of user.
175      * @param array $data
176      * @param boolean $verifyEmail
177      * @return User
178      */
179     public function create(array $data, $verifyEmail = false)
180     {
181         return $this->user->forceCreate([
182             'name'     => $data['name'],
183             'email'    => $data['email'],
184             'password' => bcrypt($data['password']),
185             'email_confirmed' => $verifyEmail
186         ]);
187     }
188
189     /**
190      * Remove the given user from storage, Delete all related content.
191      * @param User $user
192      * @throws Exception
193      */
194     public function destroy(User $user)
195     {
196         $user->socialAccounts()->delete();
197         $user->apiTokens()->delete();
198         $user->delete();
199         
200         // Delete user profile images
201         $profileImages = Image::where('type', '=', 'user')->where('uploaded_to', '=', $user->id)->get();
202         foreach ($profileImages as $image) {
203             Images::destroy($image);
204         }
205     }
206
207     /**
208      * Get the latest activity for a user.
209      * @param User $user
210      * @param int $count
211      * @param int $page
212      * @return array
213      */
214     public function getActivity(User $user, $count = 20, $page = 0)
215     {
216         return Activity::userActivity($user, $count, $page);
217     }
218
219     /**
220      * Get the recently created content for this given user.
221      */
222     public function getRecentlyCreated(User $user, int $count = 20): array
223     {
224         $query = function (Builder $query) use ($user, $count) {
225             return $query->orderBy('created_at', 'desc')
226                 ->where('created_by', '=', $user->id)
227                 ->take($count)
228                 ->get();
229         };
230
231         return [
232             'pages'    => $query(Page::visible()->where('draft', '=', false)),
233             'chapters' => $query(Chapter::visible()),
234             'books'    => $query(Book::visible()),
235             'shelves'  => $query(Bookshelf::visible()),
236         ];
237     }
238
239     /**
240      * Get asset created counts for the give user.
241      */
242     public function getAssetCounts(User $user): array
243     {
244         $createdBy = ['created_by' => $user->id];
245         return [
246             'pages'    =>  Page::visible()->where($createdBy)->count(),
247             'chapters'    =>  Chapter::visible()->where($createdBy)->count(),
248             'books'    =>  Book::visible()->where($createdBy)->count(),
249             'shelves'    =>  Bookshelf::visible()->where($createdBy)->count(),
250         ];
251     }
252
253     /**
254      * Get the roles in the system that are assignable to a user.
255      * @return mixed
256      */
257     public function getAllRoles()
258     {
259         return $this->role->newQuery()->orderBy('name', 'asc')->get();
260     }
261
262     /**
263      * Get an avatar image for a user and set it as their avatar.
264      * Returns early if avatars disabled or not set in config.
265      * @param User $user
266      * @return bool
267      */
268     public function downloadAndAssignUserAvatar(User $user)
269     {
270         if (!Images::avatarFetchEnabled()) {
271             return false;
272         }
273
274         try {
275             $avatar = Images::saveUserAvatar($user);
276             $user->avatar()->associate($avatar);
277             $user->save();
278             return true;
279         } catch (Exception $e) {
280             Log::error('Failed to save user avatar image');
281             return false;
282         }
283     }
284 }