]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/UserController.php
Increased attachment link limit from 192 to 2k
[bookstack] / app / Http / Controllers / UserController.php
1 <?php
2
3 namespace BookStack\Http\Controllers;
4
5 use BookStack\Auth\Access\SocialAuthService;
6 use BookStack\Auth\Queries\UsersAllPaginatedAndSorted;
7 use BookStack\Auth\Role;
8 use BookStack\Auth\UserRepo;
9 use BookStack\Exceptions\ImageUploadException;
10 use BookStack\Exceptions\UserUpdateException;
11 use BookStack\Uploads\ImageRepo;
12 use BookStack\Util\SimpleListOptions;
13 use Exception;
14 use Illuminate\Http\Request;
15 use Illuminate\Support\Facades\DB;
16 use Illuminate\Validation\Rules\Password;
17 use Illuminate\Validation\ValidationException;
18
19 class UserController extends Controller
20 {
21     protected UserRepo $userRepo;
22     protected ImageRepo $imageRepo;
23
24     public function __construct(UserRepo $userRepo, ImageRepo $imageRepo)
25     {
26         $this->userRepo = $userRepo;
27         $this->imageRepo = $imageRepo;
28     }
29
30     /**
31      * Display a listing of the users.
32      */
33     public function index(Request $request)
34     {
35         $this->checkPermission('users-manage');
36
37         $listOptions = SimpleListOptions::fromRequest($request, 'users')->withSortOptions([
38             'name' => trans('common.sort_name'),
39             'email' => trans('auth.email'),
40             'created_at' => trans('common.sort_created_at'),
41             'updated_at' => trans('common.sort_updated_at'),
42             'last_activity_at' => trans('settings.users_latest_activity'),
43         ]);
44
45         $users = (new UsersAllPaginatedAndSorted())->run(20, $listOptions);
46
47         $this->setPageTitle(trans('settings.users'));
48         $users->appends($listOptions->getPaginationAppends());
49
50         return view('users.index', [
51             'users'       => $users,
52             'listOptions' => $listOptions,
53         ]);
54     }
55
56     /**
57      * Show the form for creating a new user.
58      */
59     public function create()
60     {
61         $this->checkPermission('users-manage');
62         $authMethod = config('auth.method');
63         $roles = Role::query()->orderBy('display_name', 'asc')->get();
64         $this->setPageTitle(trans('settings.users_add_new'));
65
66         return view('users.create', ['authMethod' => $authMethod, 'roles' => $roles]);
67     }
68
69     /**
70      * Store a new user in storage.
71      *
72      * @throws ValidationException
73      */
74     public function store(Request $request)
75     {
76         $this->checkPermission('users-manage');
77
78         $authMethod = config('auth.method');
79         $sendInvite = ($request->get('send_invite', 'false') === 'true');
80         $externalAuth = $authMethod === 'ldap' || $authMethod === 'saml2' || $authMethod === 'oidc';
81         $passwordRequired = ($authMethod === 'standard' && !$sendInvite);
82
83         $validationRules = [
84             'name'             => ['required', 'max:100'],
85             'email'            => ['required', 'email', 'unique:users,email'],
86             'language'         => ['string', 'max:15', 'alpha_dash'],
87             'roles'            => ['array'],
88             'roles.*'          => ['integer'],
89             'password'         => $passwordRequired ? ['required', Password::default()] : null,
90             'password-confirm' => $passwordRequired ? ['required', 'same:password'] : null,
91             'external_auth_id' => $externalAuth ? ['required'] : null,
92         ];
93
94         $validated = $this->validate($request, array_filter($validationRules));
95
96         DB::transaction(function () use ($validated, $sendInvite) {
97             $this->userRepo->create($validated, $sendInvite);
98         });
99
100         return redirect('/settings/users');
101     }
102
103     /**
104      * Show the form for editing the specified user.
105      */
106     public function edit(int $id, SocialAuthService $socialAuthService)
107     {
108         $this->checkPermissionOrCurrentUser('users-manage', $id);
109
110         $user = $this->userRepo->getById($id);
111         $user->load(['apiTokens', 'mfaValues']);
112         $authMethod = ($user->system_name) ? 'system' : config('auth.method');
113
114         $activeSocialDrivers = $socialAuthService->getActiveDrivers();
115         $mfaMethods = $user->mfaValues->groupBy('method');
116         $this->setPageTitle(trans('settings.user_profile'));
117         $roles = Role::query()->orderBy('display_name', 'asc')->get();
118
119         return view('users.edit', [
120             'user'                => $user,
121             'activeSocialDrivers' => $activeSocialDrivers,
122             'mfaMethods'          => $mfaMethods,
123             'authMethod'          => $authMethod,
124             'roles'               => $roles,
125         ]);
126     }
127
128     /**
129      * Update the specified user in storage.
130      *
131      * @throws UserUpdateException
132      * @throws ImageUploadException
133      * @throws ValidationException
134      */
135     public function update(Request $request, int $id)
136     {
137         $this->preventAccessInDemoMode();
138         $this->checkPermissionOrCurrentUser('users-manage', $id);
139
140         $validated = $this->validate($request, [
141             'name'             => ['min:2', 'max:100'],
142             'email'            => ['min:2', 'email', 'unique:users,email,' . $id],
143             'password'         => ['required_with:password_confirm', Password::default()],
144             'password-confirm' => ['same:password', 'required_with:password'],
145             'language'         => ['string', 'max:15', 'alpha_dash'],
146             'roles'            => ['array'],
147             'roles.*'          => ['integer'],
148             'external_auth_id' => ['string'],
149             'profile_image'    => array_merge(['nullable'], $this->getImageValidationRules()),
150         ]);
151
152         $user = $this->userRepo->getById($id);
153         $this->userRepo->update($user, $validated, userCan('users-manage'));
154
155         // Save profile image if in request
156         if ($request->hasFile('profile_image')) {
157             $imageUpload = $request->file('profile_image');
158             $this->imageRepo->destroyImage($user->avatar);
159             $image = $this->imageRepo->saveNew($imageUpload, 'user', $user->id);
160             $user->image_id = $image->id;
161             $user->save();
162         }
163
164         // Delete the profile image if reset option is in request
165         if ($request->has('profile_image_reset')) {
166             $this->imageRepo->destroyImage($user->avatar);
167             $user->image_id = 0;
168             $user->save();
169         }
170
171         $redirectUrl = userCan('users-manage') ? '/settings/users' : "/settings/users/{$user->id}";
172
173         return redirect($redirectUrl);
174     }
175
176     /**
177      * Show the user delete page.
178      */
179     public function delete(int $id)
180     {
181         $this->checkPermissionOrCurrentUser('users-manage', $id);
182
183         $user = $this->userRepo->getById($id);
184         $this->setPageTitle(trans('settings.users_delete_named', ['userName' => $user->name]));
185
186         return view('users.delete', ['user' => $user]);
187     }
188
189     /**
190      * Remove the specified user from storage.
191      *
192      * @throws Exception
193      */
194     public function destroy(Request $request, int $id)
195     {
196         $this->preventAccessInDemoMode();
197         $this->checkPermissionOrCurrentUser('users-manage', $id);
198
199         $user = $this->userRepo->getById($id);
200         $newOwnerId = $request->get('new_owner_id', null);
201
202         $this->userRepo->destroy($user, $newOwnerId);
203
204         return redirect('/settings/users');
205     }
206 }