3 namespace BookStack\Http\Controllers;
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;
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;
20 class UserController extends Controller
24 protected $inviteService;
28 * UserController constructor.
30 public function __construct(User $user, UserRepo $userRepo, UserInviteService $inviteService, ImageRepo $imageRepo)
33 $this->userRepo = $userRepo;
34 $this->inviteService = $inviteService;
35 $this->imageRepo = $imageRepo;
39 * Display a listing of the users.
41 public function index(Request $request)
43 $this->checkPermission('users-manage');
45 'order' => $request->get('order', 'asc'),
46 'search' => $request->get('search', ''),
47 'sort' => $request->get('sort', 'name'),
49 $users = $this->userRepo->getAllUsersPaginatedAndSorted(20, $listDetails);
51 $this->setPageTitle(trans('settings.users'));
52 $users->appends($listDetails);
54 return view('users.index', ['users' => $users, 'listDetails' => $listDetails]);
58 * Show the form for creating a new user.
60 public function create()
62 $this->checkPermission('users-manage');
63 $authMethod = config('auth.method');
64 $roles = $this->userRepo->getAllRoles();
65 $this->setPageTitle(trans('settings.users_add_new'));
67 return view('users.create', ['authMethod' => $authMethod, 'roles' => $roles]);
71 * Store a newly created user in storage.
73 * @throws UserUpdateException
74 * @throws ValidationException
76 public function store(Request $request)
78 $this->checkPermission('users-manage');
80 'name' => ['required'],
81 'email' => ['required', 'email', 'unique:users,email'],
82 'setting' => ['array'],
85 $authMethod = config('auth.method');
86 $sendInvite = ($request->get('send_invite', 'false') === 'true');
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'];
94 $this->validate($request, $validationRules);
96 $user = $this->user->fill($request->all());
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');
104 $user->refreshSlug();
106 DB::transaction(function () use ($user, $sendInvite, $request) {
109 // Save user-specific settings
110 if ($request->filled('setting')) {
111 foreach ($request->get('setting') as $key => $value) {
112 setting()->putUser($user, $key, $value);
117 $this->inviteService->sendInvitation($user);
120 if ($request->filled('roles')) {
121 $roles = $request->get('roles');
122 $this->userRepo->setUserRoles($user, $roles);
125 $this->userRepo->downloadAndAssignUserAvatar($user);
127 $this->logActivity(ActivityType::USER_CREATE, $user);
130 return redirect('/settings/users');
134 * Show the form for editing the specified user.
136 public function edit(int $id, SocialAuthService $socialAuthService)
138 $this->checkPermissionOrCurrentUser('users-manage', $id);
140 /** @var User $user */
141 $user = $this->user->newQuery()->with(['apiTokens', 'mfaValues'])->findOrFail($id);
143 $authMethod = ($user->system_name) ? 'system' : config('auth.method');
145 $activeSocialDrivers = $socialAuthService->getActiveDrivers();
146 $mfaMethods = $user->mfaValues->groupBy('method');
147 $this->setPageTitle(trans('settings.user_profile'));
148 $roles = $this->userRepo->getAllRoles();
150 return view('users.edit', [
152 'activeSocialDrivers' => $activeSocialDrivers,
153 'mfaMethods' => $mfaMethods,
154 'authMethod' => $authMethod,
160 * Update the specified user in storage.
162 * @throws UserUpdateException
163 * @throws ImageUploadException
164 * @throws ValidationException
166 public function update(Request $request, int $id)
168 $this->preventAccessInDemoMode();
169 $this->checkPermissionOrCurrentUser('users-manage', $id);
171 $validated = $this->validate($request, [
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()),
182 $user = $this->userRepo->getById($id);
183 $this->userRepo->update($user, $validated, userCan('users-manage'));
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;
194 // Delete the profile image if reset option is in request
195 if ($request->has('profile_image_reset')) {
196 $this->imageRepo->destroyImage($user->avatar);
199 $redirectUrl = userCan('users-manage') ? '/settings/users' : "/settings/users/{$user->id}";
201 return redirect($redirectUrl);
205 * Show the user delete page.
207 public function delete(int $id)
209 $this->checkPermissionOrCurrentUser('users-manage', $id);
211 $user = $this->userRepo->getById($id);
212 $this->setPageTitle(trans('settings.users_delete_named', ['userName' => $user->name]));
214 return view('users.delete', ['user' => $user]);
218 * Remove the specified user from storage.
222 public function destroy(Request $request, int $id)
224 $this->preventAccessInDemoMode();
225 $this->checkPermissionOrCurrentUser('users-manage', $id);
227 $user = $this->userRepo->getById($id);
228 $newOwnerId = $request->get('new_owner_id', null);
230 $this->userRepo->destroy($user, $newOwnerId);
232 return redirect('/settings/users');
236 * Update the user's preferred book-list display setting.
238 public function switchBooksView(Request $request, int $id)
240 return $this->switchViewType($id, $request, 'books');
244 * Update the user's preferred shelf-list display setting.
246 public function switchShelvesView(Request $request, int $id)
248 return $this->switchViewType($id, $request, 'bookshelves');
252 * Update the user's preferred shelf-view book list display setting.
254 public function switchShelfView(Request $request, int $id)
256 return $this->switchViewType($id, $request, 'bookshelf');
260 * For a type of list, switch with stored view type for a user.
262 protected function switchViewType(int $userId, Request $request, string $listName)
264 $this->checkPermissionOrCurrentUser('users-manage', $userId);
266 $viewType = $request->get('view_type');
267 if (!in_array($viewType, ['grid', 'list'])) {
271 $user = $this->userRepo->getById($userId);
272 $key = $listName . '_view_type';
273 setting()->putUser($user, $key, $viewType);
275 return redirect()->back(302, [], "/settings/users/$userId");
279 * Change the stored sort type for a particular view.
281 public function changeSort(Request $request, string $id, string $type)
283 $validSortTypes = ['books', 'bookshelves', 'shelf_books'];
284 if (!in_array($type, $validSortTypes)) {
285 return redirect()->back(500);
288 return $this->changeListSort($id, $request, $type);
292 * Toggle dark mode for the current user.
294 public function toggleDarkMode()
296 $enabled = setting()->getForCurrentUser('dark-mode-enabled', false);
297 setting()->putUser(user(), 'dark-mode-enabled', $enabled ? 'false' : 'true');
299 return redirect()->back();
303 * Update the stored section expansion preference for the given user.
305 public function updateExpansionPreference(Request $request, string $id, string $key)
307 $this->checkPermissionOrCurrentUser('users-manage', $id);
308 $keyWhitelist = ['home-details'];
309 if (!in_array($key, $keyWhitelist)) {
310 return response('Invalid key', 500);
313 $newState = $request->get('expand', 'false');
315 $user = $this->user->findOrFail($id);
316 setting()->putUser($user, 'section_expansion#' . $key, $newState);
318 return response('', 204);
322 * Changed the stored preference for a list sort order.
324 protected function changeListSort(int $userId, Request $request, string $listName)
326 $this->checkPermissionOrCurrentUser('users-manage', $userId);
328 $sort = $request->get('sort');
329 if (!in_array($sort, ['name', 'created_at', 'updated_at', 'default'])) {
333 $order = $request->get('order');
334 if (!in_array($order, ['asc', 'desc'])) {
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);
344 return redirect()->back(302, [], "/settings/users/$userId");