]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/UserController.php
Merge pull request #2023 from jzoy/master
[bookstack] / app / Http / Controllers / UserController.php
1 <?php namespace BookStack\Http\Controllers;
2
3 use BookStack\Auth\Access\SocialAuthService;
4 use BookStack\Auth\Access\UserInviteService;
5 use BookStack\Auth\User;
6 use BookStack\Auth\UserRepo;
7 use BookStack\Exceptions\UserUpdateException;
8 use BookStack\Uploads\ImageRepo;
9 use Illuminate\Http\Request;
10 use Illuminate\Support\Str;
11
12 class UserController extends Controller
13 {
14
15     protected $user;
16     protected $userRepo;
17     protected $inviteService;
18     protected $imageRepo;
19
20     /**
21      * UserController constructor.
22      */
23     public function __construct(User $user, UserRepo $userRepo, UserInviteService $inviteService, ImageRepo $imageRepo)
24     {
25         $this->user = $user;
26         $this->userRepo = $userRepo;
27         $this->inviteService = $inviteService;
28         $this->imageRepo = $imageRepo;
29         parent::__construct();
30     }
31
32     /**
33      * Display a listing of the users.
34      */
35     public function index(Request $request)
36     {
37         $this->checkPermission('users-manage');
38         $listDetails = [
39             'order' => $request->get('order', 'asc'),
40             'search' => $request->get('search', ''),
41             'sort' => $request->get('sort', 'name'),
42         ];
43         $users = $this->userRepo->getAllUsersPaginatedAndSorted(20, $listDetails);
44         $this->setPageTitle(trans('settings.users'));
45         $users->appends($listDetails);
46         return view('users.index', ['users' => $users, 'listDetails' => $listDetails]);
47     }
48
49     /**
50      * Show the form for creating a new user.
51      */
52     public function create()
53     {
54         $this->checkPermission('users-manage');
55         $authMethod = config('auth.method');
56         $roles = $this->userRepo->getAllRoles();
57         return view('users.create', ['authMethod' => $authMethod, 'roles' => $roles]);
58     }
59
60     /**
61      * Store a newly created user in storage.
62      * @throws UserUpdateException
63      * @throws \Illuminate\Validation\ValidationException
64      */
65     public function store(Request $request)
66     {
67         $this->checkPermission('users-manage');
68         $validationRules = [
69             'name'             => 'required',
70             'email'            => 'required|email|unique:users,email'
71         ];
72
73         $authMethod = config('auth.method');
74         $sendInvite = ($request->get('send_invite', 'false') === 'true');
75
76         if ($authMethod === 'standard' && !$sendInvite) {
77             $validationRules['password'] = 'required|min:6';
78             $validationRules['password-confirm'] = 'required|same:password';
79         } elseif ($authMethod === 'ldap') {
80             $validationRules['external_auth_id'] = 'required';
81         }
82         $this->validate($request, $validationRules);
83
84         $user = $this->user->fill($request->all());
85
86         if ($authMethod === 'standard') {
87             $user->password = bcrypt($request->get('password', Str::random(32)));
88         } elseif ($authMethod === 'ldap') {
89             $user->external_auth_id = $request->get('external_auth_id');
90         }
91
92         $user->save();
93
94         if ($sendInvite) {
95             $this->inviteService->sendInvitation($user);
96         }
97
98         if ($request->filled('roles')) {
99             $roles = $request->get('roles');
100             $this->userRepo->setUserRoles($user, $roles);
101         }
102
103         $this->userRepo->downloadAndAssignUserAvatar($user);
104
105         return redirect('/settings/users');
106     }
107
108     /**
109      * Show the form for editing the specified user.
110      */
111     public function edit(int $id, SocialAuthService $socialAuthService)
112     {
113         $this->checkPermissionOrCurrentUser('users-manage', $id);
114
115         $user = $this->user->newQuery()->with(['apiTokens'])->findOrFail($id);
116
117         $authMethod = ($user->system_name) ? 'system' : config('auth.method');
118
119         $activeSocialDrivers = $socialAuthService->getActiveDrivers();
120         $this->setPageTitle(trans('settings.user_profile'));
121         $roles = $this->userRepo->getAllRoles();
122         return view('users.edit', [
123             'user' => $user,
124             'activeSocialDrivers' => $activeSocialDrivers,
125             'authMethod' => $authMethod,
126             'roles' => $roles
127         ]);
128     }
129
130     /**
131      * Update the specified user in storage.
132      * @throws UserUpdateException
133      * @throws \BookStack\Exceptions\ImageUploadException
134      * @throws \Illuminate\Validation\ValidationException
135      */
136     public function update(Request $request, int $id)
137     {
138         $this->preventAccessInDemoMode();
139         $this->checkPermissionOrCurrentUser('users-manage', $id);
140
141         $this->validate($request, [
142             'name'             => 'min:2',
143             'email'            => 'min:2|email|unique:users,email,' . $id,
144             'password'         => 'min:6|required_with:password_confirm',
145             'password-confirm' => 'same:password|required_with:password',
146             'setting'          => 'array',
147             'profile_image'    => 'nullable|' . $this->getImageValidationRules(),
148         ]);
149
150         $user = $this->userRepo->getById($id);
151         $user->fill($request->except(['email']));
152
153         // Email updates
154         if (userCan('users-manage') && $request->filled('email')) {
155             $user->email = $request->get('email');
156         }
157
158         // Role updates
159         if (userCan('users-manage') && $request->filled('roles')) {
160             $roles = $request->get('roles');
161             $this->userRepo->setUserRoles($user, $roles);
162         }
163
164         // Password updates
165         if ($request->filled('password')) {
166             $password = $request->get('password');
167             $user->password = bcrypt($password);
168         }
169
170         // External auth id updates
171         if (user()->can('users-manage') && $request->filled('external_auth_id')) {
172             $user->external_auth_id = $request->get('external_auth_id');
173         }
174
175         // Save an user-specific settings
176         if ($request->filled('setting')) {
177             foreach ($request->get('setting') as $key => $value) {
178                 setting()->putUser($user, $key, $value);
179             }
180         }
181
182         // Save profile image if in request
183         if ($request->hasFile('profile_image')) {
184             $imageUpload = $request->file('profile_image');
185             $this->imageRepo->destroyImage($user->avatar);
186             $image = $this->imageRepo->saveNew($imageUpload, 'user', $user->id);
187             $user->image_id = $image->id;
188         }
189
190         // Delete the profile image if set to
191         if ($request->has('profile_image_reset')) {
192             $this->imageRepo->destroyImage($user->avatar);
193         }
194
195         $user->save();
196         $this->showSuccessNotification(trans('settings.users_edit_success'));
197
198         $redirectUrl = userCan('users-manage') ? '/settings/users' : ('/settings/users/' . $user->id);
199         return redirect($redirectUrl);
200     }
201
202     /**
203      * Show the user delete page.
204      */
205     public function delete(int $id)
206     {
207         $this->checkPermissionOrCurrentUser('users-manage', $id);
208
209         $user = $this->userRepo->getById($id);
210         $this->setPageTitle(trans('settings.users_delete_named', ['userName' => $user->name]));
211         return view('users.delete', ['user' => $user]);
212     }
213
214     /**
215      * Remove the specified user from storage.
216      * @throws \Exception
217      */
218     public function destroy(int $id)
219     {
220         $this->preventAccessInDemoMode();
221         $this->checkPermissionOrCurrentUser('users-manage', $id);
222
223         $user = $this->userRepo->getById($id);
224
225         if ($this->userRepo->isOnlyAdmin($user)) {
226             $this->showErrorNotification(trans('errors.users_cannot_delete_only_admin'));
227             return redirect($user->getEditUrl());
228         }
229
230         if ($user->system_name === 'public') {
231             $this->showErrorNotification(trans('errors.users_cannot_delete_guest'));
232             return redirect($user->getEditUrl());
233         }
234
235         $this->userRepo->destroy($user);
236         $this->showSuccessNotification(trans('settings.users_delete_success'));
237
238         return redirect('/settings/users');
239     }
240
241     /**
242      * Show the user profile page
243      */
244     public function showProfilePage($id)
245     {
246         $user = $this->userRepo->getById($id);
247
248         $userActivity = $this->userRepo->getActivity($user);
249         $recentlyCreated = $this->userRepo->getRecentlyCreated($user, 5);
250         $assetCounts = $this->userRepo->getAssetCounts($user);
251
252         return view('users.profile', [
253             'user' => $user,
254             'activity' => $userActivity,
255             'recentlyCreated' => $recentlyCreated,
256             'assetCounts' => $assetCounts
257         ]);
258     }
259
260     /**
261      * Update the user's preferred book-list display setting.
262      */
263     public function switchBooksView(Request $request, int $id)
264     {
265         return $this->switchViewType($id, $request, 'books');
266     }
267
268     /**
269      * Update the user's preferred shelf-list display setting.
270      */
271     public function switchShelvesView(Request $request, int $id)
272     {
273         return $this->switchViewType($id, $request, 'bookshelves');
274     }
275
276     /**
277      * Update the user's preferred shelf-view book list display setting.
278      */
279     public function switchShelfView(Request $request, int $id)
280     {
281         return $this->switchViewType($id, $request, 'bookshelf');
282     }
283
284     /**
285      * For a type of list, switch with stored view type for a user.
286      */
287     protected function switchViewType(int $userId, Request $request, string $listName)
288     {
289         $this->checkPermissionOrCurrentUser('users-manage', $userId);
290
291         $viewType = $request->get('view_type');
292         if (!in_array($viewType, ['grid', 'list'])) {
293             $viewType = 'list';
294         }
295
296         $user = $this->userRepo->getById($userId);
297         $key = $listName . '_view_type';
298         setting()->putUser($user, $key, $viewType);
299
300         return redirect()->back(302, [], "/settings/users/$userId");
301     }
302
303     /**
304      * Change the stored sort type for a particular view.
305      */
306     public function changeSort(Request $request, string $id, string $type)
307     {
308         $validSortTypes = ['books', 'bookshelves'];
309         if (!in_array($type, $validSortTypes)) {
310             return redirect()->back(500);
311         }
312         return $this->changeListSort($id, $request, $type);
313     }
314
315     /**
316      * Toggle dark mode for the current user.
317      */
318     public function toggleDarkMode()
319     {
320         $enabled = setting()->getForCurrentUser('dark-mode-enabled', false);
321         setting()->putUser(user(), 'dark-mode-enabled', $enabled ? 'false' : 'true');
322         return redirect()->back();
323     }
324
325     /**
326      * Update the stored section expansion preference for the given user.
327      */
328     public function updateExpansionPreference(Request $request, string $id, string $key)
329     {
330         $this->checkPermissionOrCurrentUser('users-manage', $id);
331         $keyWhitelist = ['home-details'];
332         if (!in_array($key, $keyWhitelist)) {
333             return response("Invalid key", 500);
334         }
335
336         $newState = $request->get('expand', 'false');
337
338         $user = $this->user->findOrFail($id);
339         setting()->putUser($user, 'section_expansion#' . $key, $newState);
340         return response("", 204);
341     }
342
343     /**
344      * Changed the stored preference for a list sort order.
345      */
346     protected function changeListSort(int $userId, Request $request, string $listName)
347     {
348         $this->checkPermissionOrCurrentUser('users-manage', $userId);
349
350         $sort = $request->get('sort');
351         if (!in_array($sort, ['name', 'created_at', 'updated_at'])) {
352             $sort = 'name';
353         }
354
355         $order = $request->get('order');
356         if (!in_array($order, ['asc', 'desc'])) {
357             $order = 'asc';
358         }
359
360         $user = $this->user->findOrFail($userId);
361         $sortKey = $listName . '_sort';
362         $orderKey = $listName . '_sort_order';
363         setting()->putUser($user, $sortKey, $sort);
364         setting()->putUser($user, $orderKey, $order);
365
366         return redirect()->back(302, [], "/settings/users/$userId");
367     }
368 }