BookStack/app/Http/Controllers/UserController.php

382 lines
12 KiB
PHP
Raw Normal View History

2021-06-26 11:23:15 -04:00
<?php
namespace BookStack\Http\Controllers;
2015-08-08 15:05:30 -04:00
use BookStack\Actions\ActivityType;
use BookStack\Auth\Access\SocialAuthService;
2019-08-18 08:11:30 -04:00
use BookStack\Auth\Access\UserInviteService;
use BookStack\Auth\User;
use BookStack\Auth\UserRepo;
use BookStack\Exceptions\ImageUploadException;
use BookStack\Exceptions\UserUpdateException;
use BookStack\Uploads\ImageRepo;
use Exception;
use Illuminate\Http\Request;
2019-09-13 18:58:40 -04:00
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
2015-08-08 15:05:30 -04:00
class UserController extends Controller
{
protected $user;
protected $userRepo;
2019-08-18 08:11:30 -04:00
protected $inviteService;
protected $imageRepo;
2015-08-08 15:05:30 -04:00
/**
* UserController constructor.
*/
2019-08-18 08:11:30 -04:00
public function __construct(User $user, UserRepo $userRepo, UserInviteService $inviteService, ImageRepo $imageRepo)
2015-08-08 15:05:30 -04:00
{
$this->user = $user;
$this->userRepo = $userRepo;
2019-08-18 08:11:30 -04:00
$this->inviteService = $inviteService;
$this->imageRepo = $imageRepo;
2015-08-08 15:05:30 -04:00
}
/**
* Display a listing of the users.
*/
public function index(Request $request)
2015-08-08 15:05:30 -04:00
{
$this->checkPermission('users-manage');
$listDetails = [
2021-06-26 11:23:15 -04:00
'order' => $request->get('order', 'asc'),
2017-11-19 10:56:06 -05:00
'search' => $request->get('search', ''),
2021-06-26 11:23:15 -04:00
'sort' => $request->get('sort', 'name'),
];
$users = $this->userRepo->getAllUsersPaginatedAndSorted(20, $listDetails);
2016-12-04 11:51:39 -05:00
$this->setPageTitle(trans('settings.users'));
$users->appends($listDetails);
2021-06-26 11:23:15 -04:00
return view('users.index', ['users' => $users, 'listDetails' => $listDetails]);
2015-08-08 15:05:30 -04:00
}
/**
* Show the form for creating a new user.
*/
public function create()
{
$this->checkPermission('users-manage');
$authMethod = config('auth.method');
$roles = $this->userRepo->getAllRoles();
2021-06-26 11:23:15 -04:00
return view('users.create', ['authMethod' => $authMethod, 'roles' => $roles]);
2015-08-08 15:05:30 -04:00
}
/**
* Store a newly created user in storage.
2021-06-26 11:23:15 -04:00
*
* @throws UserUpdateException
* @throws ValidationException
2015-08-08 15:05:30 -04:00
*/
public function store(Request $request)
{
$this->checkPermission('users-manage');
$validationRules = [
'name' => 'required',
2021-06-26 11:23:15 -04:00
'email' => 'required|email|unique:users,email',
];
$authMethod = config('auth.method');
2019-08-18 08:11:30 -04:00
$sendInvite = ($request->get('send_invite', 'false') === 'true');
if ($authMethod === 'standard' && !$sendInvite) {
$validationRules['password'] = 'required|min:6';
$validationRules['password-confirm'] = 'required|same:password';
} elseif ($authMethod === 'ldap' || $authMethod === 'saml2' || $authMethod === 'openid') {
$validationRules['external_auth_id'] = 'required';
}
$this->validate($request, $validationRules);
2015-08-08 15:05:30 -04:00
$user = $this->user->fill($request->all());
2015-08-29 10:03:42 -04:00
if ($authMethod === 'standard') {
2019-09-13 18:58:40 -04:00
$user->password = bcrypt($request->get('password', Str::random(32)));
} elseif ($authMethod === 'ldap' || $authMethod === 'saml2' || $authMethod === 'openid') {
$user->external_auth_id = $request->get('external_auth_id');
}
$user->refreshSlug();
$user->save();
2019-08-18 08:11:30 -04:00
if ($sendInvite) {
$this->inviteService->sendInvitation($user);
}
2017-11-19 10:56:06 -05:00
if ($request->filled('roles')) {
$roles = $request->get('roles');
$this->userRepo->setUserRoles($user, $roles);
}
2015-12-14 15:13:32 -05:00
$this->userRepo->downloadAndAssignUserAvatar($user);
2015-12-14 15:13:32 -05:00
$this->logActivity(ActivityType::USER_CREATE, $user);
2021-06-26 11:23:15 -04:00
2016-02-16 16:25:11 -05:00
return redirect('/settings/users');
2015-08-08 15:05:30 -04:00
}
/**
* Show the form for editing the specified user.
*/
public function edit(int $id, SocialAuthService $socialAuthService)
2015-08-08 15:05:30 -04:00
{
$this->checkPermissionOrCurrentUser('users-manage', $id);
2015-09-04 15:40:36 -04:00
/** @var User $user */
$user = $this->user->newQuery()->with(['apiTokens', 'mfaValues'])->findOrFail($id);
$authMethod = ($user->system_name) ? 'system' : config('auth.method');
2015-09-04 15:40:36 -04:00
$activeSocialDrivers = $socialAuthService->getActiveDrivers();
$mfaMethods = $user->mfaValues->groupBy('method');
2016-12-04 11:51:39 -05:00
$this->setPageTitle(trans('settings.user_profile'));
$roles = $this->userRepo->getAllRoles();
2021-06-26 11:23:15 -04:00
return view('users.edit', [
2021-06-26 11:23:15 -04:00
'user' => $user,
'activeSocialDrivers' => $activeSocialDrivers,
2021-07-14 15:06:41 -04:00
'mfaMethods' => $mfaMethods,
2021-06-26 11:23:15 -04:00
'authMethod' => $authMethod,
'roles' => $roles,
]);
2015-08-08 15:05:30 -04:00
}
/**
* Update the specified user in storage.
2021-06-26 11:23:15 -04:00
*
* @throws UserUpdateException
* @throws ImageUploadException
* @throws ValidationException
2015-08-08 15:05:30 -04:00
*/
public function update(Request $request, int $id)
2015-08-08 15:05:30 -04:00
{
$this->preventAccessInDemoMode();
$this->checkPermissionOrCurrentUser('users-manage', $id);
2015-08-08 15:05:30 -04:00
$this->validate($request, [
'name' => 'min:2',
'email' => 'min:2|email|unique:users,email,' . $id,
2019-08-18 08:11:30 -04:00
'password' => 'min:6|required_with:password_confirm',
'password-confirm' => 'same:password|required_with:password',
'setting' => 'array',
'profile_image' => 'nullable|' . $this->getImageValidationRules(),
2015-08-08 15:05:30 -04:00
]);
$user = $this->userRepo->getById($id);
$user->fill($request->except(['email']));
// Email updates
if (userCan('users-manage') && $request->filled('email')) {
$user->email = $request->get('email');
}
2015-08-08 15:05:30 -04:00
// Refresh the slug if the user's name has changed
if ($user->isDirty('name')) {
$user->refreshSlug();
}
// Role updates
2017-11-19 10:56:06 -05:00
if (userCan('users-manage') && $request->filled('roles')) {
$roles = $request->get('roles');
$this->userRepo->setUserRoles($user, $roles);
2015-08-29 10:03:42 -04:00
}
// Password updates
2017-11-19 10:56:06 -05:00
if ($request->filled('password')) {
2015-08-08 15:05:30 -04:00
$password = $request->get('password');
$user->password = bcrypt($password);
2015-08-08 15:05:30 -04:00
}
// External auth id updates
if (user()->can('users-manage') && $request->filled('external_auth_id')) {
$user->external_auth_id = $request->get('external_auth_id');
}
// Save an user-specific settings
2017-11-19 10:56:06 -05:00
if ($request->filled('setting')) {
foreach ($request->get('setting') as $key => $value) {
setting()->putUser($user, $key, $value);
}
}
// 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;
}
// Delete the profile image if reset option is in request
if ($request->has('profile_image_reset')) {
$this->imageRepo->destroyImage($user->avatar);
}
2015-08-08 15:05:30 -04:00
$user->save();
$this->showSuccessNotification(trans('settings.users_edit_success'));
$this->logActivity(ActivityType::USER_UPDATE, $user);
$redirectUrl = userCan('users-manage') ? '/settings/users' : ('/settings/users/' . $user->id);
2021-06-26 11:23:15 -04:00
return redirect($redirectUrl);
2015-08-08 15:05:30 -04:00
}
/**
* Show the user delete page.
*/
public function delete(int $id)
2015-08-08 15:05:30 -04:00
{
$this->checkPermissionOrCurrentUser('users-manage', $id);
$user = $this->userRepo->getById($id);
2016-12-04 11:51:39 -05:00
$this->setPageTitle(trans('settings.users_delete_named', ['userName' => $user->name]));
2021-06-26 11:23:15 -04:00
return view('users.delete', ['user' => $user]);
2015-08-08 15:05:30 -04:00
}
/**
* Remove the specified user from storage.
2021-06-26 11:23:15 -04:00
*
* @throws Exception
2015-08-08 15:05:30 -04:00
*/
public function destroy(Request $request, int $id)
2015-08-08 15:05:30 -04:00
{
$this->preventAccessInDemoMode();
$this->checkPermissionOrCurrentUser('users-manage', $id);
2015-12-14 15:13:32 -05:00
$user = $this->userRepo->getById($id);
$newOwnerId = $request->get('new_owner_id', null);
2015-12-14 15:13:32 -05:00
if ($this->userRepo->isOnlyAdmin($user)) {
$this->showErrorNotification(trans('errors.users_cannot_delete_only_admin'));
2021-06-26 11:23:15 -04:00
return redirect($user->getEditUrl());
}
if ($user->system_name === 'public') {
$this->showErrorNotification(trans('errors.users_cannot_delete_guest'));
2021-06-26 11:23:15 -04:00
return redirect($user->getEditUrl());
}
$this->userRepo->destroy($user, $newOwnerId);
$this->showSuccessNotification(trans('settings.users_delete_success'));
$this->logActivity(ActivityType::USER_DELETE, $user);
2015-12-14 15:13:32 -05:00
2016-02-16 16:25:11 -05: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)
{
2021-01-30 22:25:31 -05:00
$validSortTypes = ['books', 'bookshelves', 'shelf_books'];
if (!in_array($type, $validSortTypes)) {
return redirect()->back(500);
}
2021-06-26 11:23:15 -04:00
return $this->changeListSort($id, $request, $type);
}
/**
* 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 11:23:15 -04: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 11:23:15 -04:00
return response('Invalid key', 500);
}
$newState = $request->get('expand', 'false');
$user = $this->user->findOrFail($id);
setting()->putUser($user, 'section_expansion#' . $key, $newState);
2021-06-26 11:23:15 -04:00
return response('', 204);
}
/**
* Changed the stored preference for a list sort order.
*/
protected function changeListSort(int $userId, Request $request, string $listName)
{
$this->checkPermissionOrCurrentUser('users-manage', $userId);
$sort = $request->get('sort');
if (!in_array($sort, ['name', 'created_at', 'updated_at', 'default'])) {
$sort = 'name';
}
$order = $request->get('order');
if (!in_array($order, ['asc', 'desc'])) {
$order = 'asc';
}
$user = $this->user->findOrFail($userId);
$sortKey = $listName . '_sort';
$orderKey = $listName . '_sort_order';
setting()->putUser($user, $sortKey, $sort);
setting()->putUser($user, $orderKey, $order);
return redirect()->back(302, [], "/settings/users/$userId");
}
2015-08-08 15:05:30 -04:00
}