3 namespace BookStack\Http\Controllers\Api;
5 use BookStack\Auth\User;
6 use BookStack\Auth\UserRepo;
8 use Illuminate\Http\Request;
9 use Illuminate\Validation\Rules\Password;
10 use Illuminate\Validation\Rules\Unique;
12 class UserApiController extends ApiController
16 protected $fieldsToExpose = [
17 'email', 'created_at', 'updated_at', 'last_activity_at', 'external_auth_id'
20 public function __construct(UserRepo $userRepo)
22 $this->userRepo = $userRepo;
25 protected function rules(int $userId = null): array
35 (new Unique('users', 'email'))->ignore($userId ?? null)
37 'external_auth_id' => ['string'],
38 'language' => ['string'],
39 'password' => [Password::default()],
41 'roles.*' => ['integer'],
44 'migrate_ownership_id' => ['integer', 'exists:users,id'],
50 * Get a listing of users in the system.
51 * Requires permission to manage users.
53 public function list()
55 $this->checkPermission('users-manage');
57 $users = $this->userRepo->getApiUsersBuilder();
59 return $this->apiListingResponse($users, [
60 'id', 'name', 'slug', 'email', 'external_auth_id',
61 'created_at', 'updated_at', 'last_activity_at',
62 ], [Closure::fromCallable([$this, 'listFormatter'])]);
66 * View the details of a single user.
67 * Requires permission to manage users.
69 public function read(string $id)
71 $this->checkPermission('users-manage');
73 $user = $this->userRepo->getById($id);
74 $this->singleFormatter($user);
76 return response()->json($user);
80 * Update an existing user in the system.
81 * @throws \BookStack\Exceptions\UserUpdateException
83 public function update(Request $request, string $id)
85 $this->checkPermission('users-manage');
87 $data = $this->validate($request, $this->rules($id)['update']);
88 $user = $this->userRepo->getById($id);
89 $this->userRepo->update($user, $data, userCan('users-manage'));
90 $this->singleFormatter($user);
92 return response()->json($user);
96 * Delete a user from the system.
97 * Can optionally accept a user id via `migrate_ownership_id` to indicate
98 * who should be the new owner of their related content.
99 * Requires permission to manage users.
101 public function delete(Request $request, string $id)
103 $this->checkPermission('users-manage');
105 $user = $this->userRepo->getById($id);
106 $newOwnerId = $request->get('migrate_ownership_id', null);
108 $this->userRepo->destroy($user, $newOwnerId);
110 return response('', 204);
114 * Format the given user model for single-result display.
116 protected function singleFormatter(User $user)
118 $this->listFormatter($user);
119 $user->load('roles:id,display_name');
120 $user->makeVisible(['roles']);
124 * Format the given user model for a listing multi-result display.
126 protected function listFormatter(User $user)
128 $user->makeVisible($this->fieldsToExpose);
129 $user->setAttribute('profile_url', $user->getProfileUrl());
130 $user->setAttribute('edit_url', $user->getEditUrl());
131 $user->setAttribute('avatar_url', $user->getAvatar());