BookStack/app/Http/Controllers/UserController.php

328 lines
11 KiB
PHP
Raw Normal View History

2021-06-26 23:23:15 +08:00
<?php
namespace BookStack\Http\Controllers;
2015-08-09 03:05:30 +08:00
use BookStack\Auth\Access\SocialAuthService;
use BookStack\Auth\Queries\UsersAllPaginatedAndSorted;
2022-02-13 20:56:26 +08:00
use BookStack\Auth\Role;
use BookStack\Auth\User;
use BookStack\Auth\UserRepo;
use BookStack\Exceptions\ImageUploadException;
use BookStack\Exceptions\UserUpdateException;
use BookStack\Uploads\ImageRepo;
use BookStack\Util\SimpleListOptions;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\ValidationException;
2015-08-09 03:05:30 +08:00
class UserController extends Controller
{
protected UserRepo $userRepo;
protected ImageRepo $imageRepo;
2015-08-09 03:05:30 +08:00
/**
* UserController constructor.
*/
public function __construct(UserRepo $userRepo, ImageRepo $imageRepo)
2015-08-09 03:05:30 +08:00
{
$this->userRepo = $userRepo;
$this->imageRepo = $imageRepo;
2015-08-09 03:05:30 +08:00
}
/**
* Display a listing of the users.
*/
public function index(Request $request)
2015-08-09 03:05:30 +08:00
{
$this->checkPermission('users-manage');
2022-02-13 20:56:26 +08:00
$listOptions = SimpleListOptions::fromRequest($request, 'users')->withSortOptions([
'name' => trans('common.sort_name'),
'email' => trans('auth.email'),
'created_at' => trans('common.sort_created_at'),
'updated_at' => trans('common.sort_updated_at'),
'last_activity_at' => trans('settings.users_latest_activity'),
]);
$users = (new UsersAllPaginatedAndSorted())->run(20, $listOptions);
2016-12-05 00:51:39 +08:00
$this->setPageTitle(trans('settings.users'));
$users->appends($listOptions->getPaginationAppends());
2021-06-26 23:23:15 +08:00
2022-02-13 20:56:26 +08:00
return view('users.index', [
'users' => $users,
'listOptions' => $listOptions,
2022-02-13 20:56:26 +08:00
]);
2015-08-09 03:05:30 +08:00
}
/**
* Show the form for creating a new user.
*/
public function create()
{
$this->checkPermission('users-manage');
$authMethod = config('auth.method');
2022-02-13 20:56:26 +08:00
$roles = Role::query()->orderBy('display_name', 'asc')->get();
$this->setPageTitle(trans('settings.users_add_new'));
2021-06-26 23:23:15 +08:00
return view('users.create', ['authMethod' => $authMethod, 'roles' => $roles]);
2015-08-09 03:05:30 +08:00
}
/**
* Store a new user in storage.
2021-06-26 23:23:15 +08:00
*
* @throws ValidationException
2015-08-09 03:05:30 +08:00
*/
public function store(Request $request)
{
$this->checkPermission('users-manage');
$authMethod = config('auth.method');
2019-08-18 20:11:30 +08:00
$sendInvite = ($request->get('send_invite', 'false') === 'true');
$externalAuth = $authMethod === 'ldap' || $authMethod === 'saml2' || $authMethod === 'oidc';
$passwordRequired = ($authMethod === 'standard' && !$sendInvite);
2019-08-18 20:11:30 +08:00
$validationRules = [
'name' => ['required', 'max:100'],
2022-02-08 23:29:58 +08:00
'email' => ['required', 'email', 'unique:users,email'],
'language' => ['string', 'max:15', 'alpha_dash'],
'roles' => ['array'],
'roles.*' => ['integer'],
2022-02-08 23:29:58 +08:00
'password' => $passwordRequired ? ['required', Password::default()] : null,
'password-confirm' => $passwordRequired ? ['required', 'same:password'] : null,
'external_auth_id' => $externalAuth ? ['required'] : null,
];
$validated = $this->validate($request, array_filter($validationRules));
DB::transaction(function () use ($validated, $sendInvite) {
$this->userRepo->create($validated, $sendInvite);
});
2021-06-26 23:23:15 +08:00
2016-02-17 05:25:11 +08:00
return redirect('/settings/users');
2015-08-09 03:05:30 +08:00
}
/**
* Show the form for editing the specified user.
*/
public function edit(int $id, SocialAuthService $socialAuthService)
2015-08-09 03:05:30 +08:00
{
$this->checkPermissionOrCurrentUser('users-manage', $id);
2015-09-05 03:40:36 +08:00
/** @var User $user */
$user = User::query()->with(['apiTokens', 'mfaValues'])->findOrFail($id);
$authMethod = ($user->system_name) ? 'system' : config('auth.method');
2015-09-05 03:40:36 +08:00
$activeSocialDrivers = $socialAuthService->getActiveDrivers();
$mfaMethods = $user->mfaValues->groupBy('method');
2016-12-05 00:51:39 +08:00
$this->setPageTitle(trans('settings.user_profile'));
2022-02-13 20:56:26 +08:00
$roles = Role::query()->orderBy('display_name', 'asc')->get();
2021-06-26 23:23:15 +08:00
return view('users.edit', [
2021-06-26 23:23:15 +08:00
'user' => $user,
'activeSocialDrivers' => $activeSocialDrivers,
2021-07-15 03:06:41 +08:00
'mfaMethods' => $mfaMethods,
2021-06-26 23:23:15 +08:00
'authMethod' => $authMethod,
'roles' => $roles,
]);
2015-08-09 03:05:30 +08:00
}
/**
* Update the specified user in storage.
2021-06-26 23:23:15 +08:00
*
* @throws UserUpdateException
* @throws ImageUploadException
* @throws ValidationException
2015-08-09 03:05:30 +08:00
*/
public function update(Request $request, int $id)
2015-08-09 03:05:30 +08:00
{
$this->preventAccessInDemoMode();
$this->checkPermissionOrCurrentUser('users-manage', $id);
$validated = $this->validate($request, [
'name' => ['min:2', 'max:100'],
'email' => ['min:2', 'email', 'unique:users,email,' . $id],
'password' => ['required_with:password_confirm', Password::default()],
'password-confirm' => ['same:password', 'required_with:password'],
'language' => ['string', 'max:15', 'alpha_dash'],
'roles' => ['array'],
'roles.*' => ['integer'],
'external_auth_id' => ['string'],
'profile_image' => array_merge(['nullable'], $this->getImageValidationRules()),
2015-08-09 03:05:30 +08:00
]);
$user = $this->userRepo->getById($id);
$this->userRepo->update($user, $validated, userCan('users-manage'));
// Save profile image if in request
if ($request->hasFile('profile_image')) {
$imageUpload = $request->file('profile_image');
$this->imageRepo->destroyImage($user->avatar);
$image = $this->imageRepo->saveNew($imageUpload, 'user', $user->id);
$user->image_id = $image->id;
$user->save();
}
// Delete the profile image if reset option is in request
if ($request->has('profile_image_reset')) {
$this->imageRepo->destroyImage($user->avatar);
}
$redirectUrl = userCan('users-manage') ? '/settings/users' : "/settings/users/{$user->id}";
2021-06-26 23:23:15 +08:00
return redirect($redirectUrl);
2015-08-09 03:05:30 +08:00
}
/**
* Show the user delete page.
*/
public function delete(int $id)
2015-08-09 03:05:30 +08:00
{
$this->checkPermissionOrCurrentUser('users-manage', $id);
$user = $this->userRepo->getById($id);
2016-12-05 00:51:39 +08:00
$this->setPageTitle(trans('settings.users_delete_named', ['userName' => $user->name]));
2021-06-26 23:23:15 +08:00
return view('users.delete', ['user' => $user]);
2015-08-09 03:05:30 +08:00
}
/**
* Remove the specified user from storage.
2021-06-26 23:23:15 +08:00
*
* @throws Exception
2015-08-09 03:05:30 +08:00
*/
public function destroy(Request $request, int $id)
2015-08-09 03:05:30 +08:00
{
$this->preventAccessInDemoMode();
$this->checkPermissionOrCurrentUser('users-manage', $id);
2015-12-15 04:13:32 +08:00
$user = $this->userRepo->getById($id);
$newOwnerId = $request->get('new_owner_id', null);
$this->userRepo->destroy($user, $newOwnerId);
2015-12-15 04:13:32 +08:00
2016-02-17 05:25:11 +08:00
return redirect('/settings/users');
}
/**
* Update the user's preferred book-list display setting.
*/
public function switchBooksView(Request $request, int $id)
{
return $this->switchViewType($id, $request, 'books');
}
/**
* Update the user's preferred shelf-list display setting.
*/
public function switchShelvesView(Request $request, int $id)
{
return $this->switchViewType($id, $request, 'bookshelves');
}
/**
* Update the user's preferred shelf-view book list display setting.
*/
public function switchShelfView(Request $request, int $id)
{
return $this->switchViewType($id, $request, 'bookshelf');
}
/**
* For a type of list, switch with stored view type for a user.
*/
protected function switchViewType(int $userId, Request $request, string $listName)
{
$this->checkPermissionOrCurrentUser('users-manage', $userId);
$viewType = $request->get('view_type');
if (!in_array($viewType, ['grid', 'list'])) {
$viewType = 'list';
}
$user = $this->userRepo->getById($userId);
$key = $listName . '_view_type';
setting()->putUser($user, $key, $viewType);
return redirect()->back(302, [], "/settings/users/$userId");
}
/**
* Change the stored sort type for a particular view.
*/
public function changeSort(Request $request, string $id, string $type)
{
$validSortTypes = ['books', 'bookshelves', 'shelf_books', 'users', 'roles', 'webhooks'];
if (!in_array($type, $validSortTypes)) {
return redirect()->back(500);
}
2021-06-26 23:23:15 +08:00
$this->checkPermissionOrCurrentUser('users-manage', $id);
$sort = substr($request->get('sort') ?: 'name', 0, 50);
$order = $request->get('order') === 'desc' ? 'desc' : 'asc';
$user = $this->userRepo->getById($id);
$sortKey = $type . '_sort';
$orderKey = $type . '_sort_order';
setting()->putUser($user, $sortKey, $sort);
setting()->putUser($user, $orderKey, $order);
return redirect()->back(302, [], "/settings/users/{$id}");
}
/**
* Toggle dark mode for the current user.
*/
public function toggleDarkMode()
{
$enabled = setting()->getForCurrentUser('dark-mode-enabled', false);
setting()->putUser(user(), 'dark-mode-enabled', $enabled ? 'false' : 'true');
2021-06-26 23:23:15 +08:00
return redirect()->back();
}
/**
* Update the stored section expansion preference for the given user.
*/
public function updateExpansionPreference(Request $request, string $id, string $key)
{
$this->checkPermissionOrCurrentUser('users-manage', $id);
$keyWhitelist = ['home-details'];
if (!in_array($key, $keyWhitelist)) {
2021-06-26 23:23:15 +08:00
return response('Invalid key', 500);
}
$newState = $request->get('expand', 'false');
$user = $this->userRepo->getById($id);
setting()->putUser($user, 'section_expansion#' . $key, $newState);
2021-06-26 23:23:15 +08:00
return response('', 204);
}
public function updateCodeLanguageFavourite(Request $request)
{
$validated = $this->validate($request, [
'language' => ['required', 'string', 'max:20'],
'active' => ['required', 'bool'],
]);
$currentFavoritesStr = setting()->getForCurrentUser('code-language-favourites', '');
$currentFavorites = array_filter(explode(',', $currentFavoritesStr));
$isFav = in_array($validated['language'], $currentFavorites);
if (!$isFav && $validated['active']) {
$currentFavorites[] = $validated['language'];
} elseif ($isFav && !$validated['active']) {
$index = array_search($validated['language'], $currentFavorites);
array_splice($currentFavorites, $index, 1);
}
setting()->putUser(user(), 'code-language-favourites', implode(',', $currentFavorites));
}
2015-08-09 03:05:30 +08:00
}