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