]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/Api/UserApiController.php
Revamped workings of WYSIWYG code blocks
[bookstack] / app / Http / Controllers / Api / UserApiController.php
1 <?php
2
3 namespace BookStack\Http\Controllers\Api;
4
5 use BookStack\Auth\User;
6 use BookStack\Auth\UserRepo;
7 use BookStack\Exceptions\UserUpdateException;
8 use Closure;
9 use Illuminate\Http\Request;
10 use Illuminate\Support\Facades\DB;
11 use Illuminate\Validation\Rules\Password;
12 use Illuminate\Validation\Rules\Unique;
13
14 class UserApiController extends ApiController
15 {
16     protected $userRepo;
17
18     protected $fieldsToExpose = [
19         'email', 'created_at', 'updated_at', 'last_activity_at', 'external_auth_id',
20     ];
21
22     public function __construct(UserRepo $userRepo)
23     {
24         $this->userRepo = $userRepo;
25
26         // Checks for all endpoints in this controller
27         $this->middleware(function ($request, $next) {
28             $this->checkPermission('users-manage');
29             $this->preventAccessInDemoMode();
30
31             return $next($request);
32         });
33     }
34
35     protected function rules(int $userId = null): array
36     {
37         return [
38             'create' => [
39                 'name'  => ['required', 'min:2'],
40                 'email' => [
41                     'required', 'min:2', 'email', new Unique('users', 'email'),
42                 ],
43                 'external_auth_id' => ['string'],
44                 'language'         => ['string'],
45                 'password'         => [Password::default()],
46                 'roles'            => ['array'],
47                 'roles.*'          => ['integer'],
48                 'send_invite'      => ['boolean'],
49             ],
50             'update' => [
51                 'name'  => ['min:2'],
52                 'email' => [
53                     'min:2',
54                     'email',
55                     (new Unique('users', 'email'))->ignore($userId ?? null),
56                 ],
57                 'external_auth_id' => ['string'],
58                 'language'         => ['string'],
59                 'password'         => [Password::default()],
60                 'roles'            => ['array'],
61                 'roles.*'          => ['integer'],
62             ],
63             'delete' => [
64                 'migrate_ownership_id' => ['integer', 'exists:users,id'],
65             ],
66         ];
67     }
68
69     /**
70      * Get a listing of users in the system.
71      * Requires permission to manage users.
72      */
73     public function list()
74     {
75         $users = $this->userRepo->getApiUsersBuilder();
76
77         return $this->apiListingResponse($users, [
78             'id', 'name', 'slug', 'email', 'external_auth_id',
79             'created_at', 'updated_at', 'last_activity_at',
80         ], [Closure::fromCallable([$this, 'listFormatter'])]);
81     }
82
83     /**
84      * Create a new user in the system.
85      * Requires permission to manage users.
86      */
87     public function create(Request $request)
88     {
89         $data = $this->validate($request, $this->rules()['create']);
90         $sendInvite = ($data['send_invite'] ?? false) === true;
91
92         $user = null;
93         DB::transaction(function () use ($data, $sendInvite, &$user) {
94             $user = $this->userRepo->create($data, $sendInvite);
95         });
96
97         $this->singleFormatter($user);
98
99         return response()->json($user);
100     }
101
102     /**
103      * View the details of a single user.
104      * Requires permission to manage users.
105      */
106     public function read(string $id)
107     {
108         $user = $this->userRepo->getById($id);
109         $this->singleFormatter($user);
110
111         return response()->json($user);
112     }
113
114     /**
115      * Update an existing user in the system.
116      * Requires permission to manage users.
117      *
118      * @throws UserUpdateException
119      */
120     public function update(Request $request, string $id)
121     {
122         $data = $this->validate($request, $this->rules($id)['update']);
123         $user = $this->userRepo->getById($id);
124         $this->userRepo->update($user, $data, userCan('users-manage'));
125         $this->singleFormatter($user);
126
127         return response()->json($user);
128     }
129
130     /**
131      * Delete a user from the system.
132      * Can optionally accept a user id via `migrate_ownership_id` to indicate
133      * who should be the new owner of their related content.
134      * Requires permission to manage users.
135      */
136     public function delete(Request $request, string $id)
137     {
138         $user = $this->userRepo->getById($id);
139         $newOwnerId = $request->get('migrate_ownership_id', null);
140
141         $this->userRepo->destroy($user, $newOwnerId);
142
143         return response('', 204);
144     }
145
146     /**
147      * Format the given user model for single-result display.
148      */
149     protected function singleFormatter(User $user)
150     {
151         $this->listFormatter($user);
152         $user->load('roles:id,display_name');
153         $user->makeVisible(['roles']);
154     }
155
156     /**
157      * Format the given user model for a listing multi-result display.
158      */
159     protected function listFormatter(User $user)
160     {
161         $user->makeVisible($this->fieldsToExpose);
162         $user->setAttribute('profile_url', $user->getProfileUrl());
163         $user->setAttribute('edit_url', $user->getEditUrl());
164         $user->setAttribute('avatar_url', $user->getAvatar());
165     }
166 }