1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2025-10-22 07:52:19 +03:00
Files
bookstack/app/Users/Controllers/UserApiController.php
Dan Brown 4c7d6420ee DB: Aligned entity structure to a common table
As per PR #5800

* DB: Planned out new entity table format via migrations

* DB: Created entity migration logic

Made some other tweaks/fixes while testing.

* DB: Added change of entity relation columns to suit new entities table

* DB: Got most view queries working for new structure

* Entities: Started logic change to new structure

Updated base entity class, and worked through BaseRepo.
Need to go through other repos next.

Removed a couple of redundant interfaces as part of this since we can
move the logic onto the shared ContainerData model as needed.

* Entities: Been through repos to update for new format

* Entities: Updated repos to act on refreshed clones

Changes to core entity models are now done on clones to ensure clean
state before save, and those clones are returned back if changes are
needed after that action.

* Entities: Updated model classes & relations for changes

* Entities: Changed from *Data to a common "contents" system

Added smart loading from builder instances which should hydrate with
"contents()" loaded via join, while keeping the core model original.

* Entities: Moved entity description/covers to own non-model classes

Added back some interfaces.

* Entities: Removed use of contents system for data access

* Entities: Got most queries back to working order

* Entities: Reverted back to data from contents, fixed various issues

* Entities: Started addressing issues from tests

* Entities: Addressed further tests/issues

* Entities: Been through tests to get all passing in dev

Fixed issues and needed test changes along the way.

* Entities: Addressed phpstan errors

* Entities: Reviewed TODO notes

* Entities: Ensured book/shelf relation data removed on destroy

* Entities: Been through API responses & adjusted field visibility

* Entities: Added type index to massively improve query speed
2025-10-18 13:14:30 +01:00

172 lines
5.3 KiB
PHP

<?php
namespace BookStack\Users\Controllers;
use BookStack\Entities\EntityExistsRule;
use BookStack\Exceptions\UserUpdateException;
use BookStack\Http\ApiController;
use BookStack\Permissions\Permission;
use BookStack\Users\Models\User;
use BookStack\Users\UserRepo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\Rules\Unique;
class UserApiController extends ApiController
{
protected UserRepo $userRepo;
protected array $fieldsToExpose = [
'email', 'created_at', 'updated_at', 'last_activity_at', 'external_auth_id',
];
public function __construct(UserRepo $userRepo)
{
$this->userRepo = $userRepo;
// Checks for all endpoints in this controller
$this->middleware(function ($request, $next) {
$this->checkPermission(Permission::UsersManage);
$this->preventAccessInDemoMode();
return $next($request);
});
}
protected function rules(?int $userId = null): array
{
return [
'create' => [
'name' => ['required', 'string', 'min:1', 'max:100'],
'email' => [
'required', 'string', 'email', 'min:2', new Unique('users', 'email'),
],
'external_auth_id' => ['string'],
'language' => ['string', 'max:15', 'alpha_dash'],
'password' => ['string', Password::default()],
'roles' => ['array'],
'roles.*' => ['integer'],
'send_invite' => ['boolean'],
],
'update' => [
'name' => ['string', 'min:1', 'max:100'],
'email' => [
'string',
'email',
'min:2',
(new Unique('users', 'email'))->ignore($userId),
],
'external_auth_id' => ['string'],
'language' => ['string', 'max:15', 'alpha_dash'],
'password' => ['string', Password::default()],
'roles' => ['array'],
'roles.*' => ['integer'],
],
'delete' => [
'migrate_ownership_id' => ['integer', 'exists:users,id'],
],
];
}
/**
* Get a listing of users in the system.
* Requires permission to manage users.
*/
public function list()
{
$users = User::query()->select(['users.*'])
->scopes('withLastActivityAt')
->with(['avatar']);
return $this->apiListingResponse($users, [
'id', 'name', 'slug', 'email', 'external_auth_id',
'created_at', 'updated_at', 'last_activity_at',
], [$this->listFormatter(...)]);
}
/**
* Create a new user in the system.
* Requires permission to manage users.
*/
public function create(Request $request)
{
$data = $this->validate($request, $this->rules()['create']);
$sendInvite = boolval($data['send_invite'] ?? false) === true;
$user = null;
DB::transaction(function () use ($data, $sendInvite, &$user) {
$user = $this->userRepo->create($data, $sendInvite);
});
$this->singleFormatter($user);
return response()->json($user);
}
/**
* View the details of a single user.
* Requires permission to manage users.
*/
public function read(string $id)
{
$user = $this->userRepo->getById($id);
$this->singleFormatter($user);
return response()->json($user);
}
/**
* Update an existing user in the system.
* Requires permission to manage users.
*
* @throws UserUpdateException
*/
public function update(Request $request, string $id)
{
$data = $this->validate($request, $this->rules($id)['update']);
$user = $this->userRepo->getById($id);
$this->userRepo->update($user, $data, userCan(Permission::UsersManage));
$this->singleFormatter($user);
return response()->json($user);
}
/**
* Delete a user from the system.
* Can optionally accept a user id via `migrate_ownership_id` to indicate
* who should be the new owner of their related content.
* Requires permission to manage users.
*/
public function delete(Request $request, string $id)
{
$user = $this->userRepo->getById($id);
$newOwnerId = $request->get('migrate_ownership_id', null);
$this->userRepo->destroy($user, $newOwnerId);
return response('', 204);
}
/**
* Format the given user model for single-result display.
*/
protected function singleFormatter(User $user)
{
$this->listFormatter($user);
$user->load('roles:id,display_name');
$user->makeVisible(['roles']);
}
/**
* Format the given user model for a listing multi-result display.
*/
protected function listFormatter(User $user)
{
$user->makeVisible($this->fieldsToExpose);
$user->setAttribute('profile_url', $user->getProfileUrl());
$user->setAttribute('edit_url', $user->getEditUrl());
$user->setAttribute('avatar_url', $user->getAvatar());
}
}