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