240 lines
8.4 KiB
PHP
240 lines
8.4 KiB
PHP
<?php
|
|
|
|
use MintyPHP\Http\ApiAuth;
|
|
use MintyPHP\Http\ApiBootstrap;
|
|
use MintyPHP\Http\ApiResponse;
|
|
use MintyPHP\Service\Access\AccessServicesFactory;
|
|
use MintyPHP\Service\Access\AuthorizationDecision;
|
|
use MintyPHP\Service\Access\UserAuthorizationPolicy;
|
|
use MintyPHP\Service\User\UserServicesFactory;
|
|
|
|
ApiBootstrap::init();
|
|
$authorizationService = (new AccessServicesFactory())->createAuthorizationService();
|
|
$userServicesFactory = new UserServicesFactory();
|
|
$userAccountService = $userServicesFactory->createUserAccountService();
|
|
$apiDeny = static function (AuthorizationDecision $decision): void {
|
|
if ($decision->isAllowed()) {
|
|
return;
|
|
}
|
|
|
|
$status = $decision->status();
|
|
$error = $decision->error() !== '' ? $decision->error() : 'forbidden';
|
|
|
|
if ($status === 401) {
|
|
ApiResponse::unauthorized();
|
|
}
|
|
if ($status === 404) {
|
|
ApiResponse::notFound($error);
|
|
}
|
|
if ($status === 403) {
|
|
ApiResponse::forbidden($error);
|
|
}
|
|
|
|
ApiResponse::error($error, $status > 0 ? $status : 403);
|
|
};
|
|
|
|
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
|
|
|
if ($method === 'GET') {
|
|
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_GET, [
|
|
'actor_user_id' => ApiAuth::userId(),
|
|
]);
|
|
$apiDeny($decision);
|
|
|
|
$limit = max(1, min(100, (int) ($_GET['limit'] ?? 25)));
|
|
$offset = max(0, (int) ($_GET['offset'] ?? 0));
|
|
$allowedOrders = ['id', 'uuid', 'first_name', 'last_name', 'display_name', 'email', 'created', 'modified', 'active', 'last_login_at'];
|
|
$order = in_array($_GET['order'] ?? '', $allowedOrders, true) ? $_GET['order'] : 'last_name';
|
|
$dir = in_array(strtolower($_GET['dir'] ?? ''), ['asc', 'desc'], true) ? strtolower($_GET['dir']) : 'asc';
|
|
$activeParam = $_GET['active'] ?? null;
|
|
if ($activeParam !== null) {
|
|
$activeParam = in_array($activeParam, ['0', '1', 'true', 'false'], true) ? $activeParam : null;
|
|
}
|
|
$options = [
|
|
'limit' => $limit,
|
|
'offset' => $offset,
|
|
'search' => trim((string) ($_GET['search'] ?? '')),
|
|
'order' => $order,
|
|
'dir' => $dir,
|
|
'active' => $activeParam,
|
|
'tenantUserId' => ApiAuth::userId(),
|
|
];
|
|
$scopedTenantId = ApiAuth::scopedTenantId();
|
|
if ($scopedTenantId) {
|
|
$tenant = directoryServicesFactory()->createTenantService()->findById($scopedTenantId);
|
|
$tenantUuid = trim((string) ($tenant['uuid'] ?? ''));
|
|
if ($tenantUuid === '') {
|
|
ApiResponse::notFound();
|
|
}
|
|
$options['tenant'] = $tenantUuid;
|
|
}
|
|
$result = $userAccountService->listPaged($options);
|
|
|
|
$rows = [];
|
|
foreach ($result['rows'] as $row) {
|
|
$rows[] = [
|
|
'uuid' => $row['uuid'] ?? '',
|
|
'first_name' => $row['first_name'] ?? '',
|
|
'last_name' => $row['last_name'] ?? '',
|
|
'display_name' => $row['display_name'] ?? '',
|
|
'email' => $row['email'] ?? '',
|
|
'job_title' => $row['job_title'] ?? '',
|
|
'phone' => $row['phone'] ?? '',
|
|
'mobile' => $row['mobile'] ?? '',
|
|
'active' => (bool) ($row['active'] ?? 1),
|
|
'created' => $row['created'] ?? '',
|
|
'tenants' => $row['tenant_labels'] ?? [],
|
|
'departments' => $row['department_labels'] ?? [],
|
|
'roles' => $row['role_labels'] ?? [],
|
|
];
|
|
}
|
|
|
|
ApiResponse::success([
|
|
'data' => $rows,
|
|
'total' => $result['total'] ?? 0,
|
|
'limit' => $limit,
|
|
'offset' => $offset,
|
|
]);
|
|
}
|
|
|
|
if ($method === 'POST') {
|
|
$input = ApiResponse::readJsonBody();
|
|
$normalizeResult = normalizeUserWriteInputToInternalIds($input);
|
|
if ($normalizeResult['ok'] !== true) {
|
|
$errors = $normalizeResult['errors'] ?? [];
|
|
ApiResponse::validationError($errors ?: ['input' => ['invalid_value']]);
|
|
}
|
|
$input = $normalizeResult['input'] ?? $input;
|
|
|
|
$decision = $authorizationService->authorize(UserAuthorizationPolicy::ABILITY_API_USERS_INDEX_POST, [
|
|
'actor_user_id' => ApiAuth::userId(),
|
|
'scoped_tenant_id' => ApiAuth::scopedTenantId(),
|
|
'input' => $input,
|
|
]);
|
|
$apiDeny($decision);
|
|
$authorizedInput = $decision->attribute('input', null);
|
|
if (is_array($authorizedInput)) {
|
|
$input = $authorizedInput;
|
|
}
|
|
|
|
$result = $userAccountService->createFromAdmin($input, ApiAuth::userId());
|
|
ApiResponse::fromServiceResult($result, 201);
|
|
}
|
|
|
|
ApiResponse::methodNotAllowed();
|
|
|
|
/**
|
|
* Normalize public UUID-based assignment payload to internal IDs used by services.
|
|
*
|
|
* @param array<string, mixed> $input
|
|
* @return array{ok: bool, input?: array<string, mixed>, errors?: array<string, array<int, string>>}
|
|
*/
|
|
function normalizeUserWriteInputToInternalIds(array $input): array
|
|
{
|
|
$errors = [];
|
|
foreach ([
|
|
'tenant_ids' => 'use_tenant_uuids',
|
|
'primary_tenant_id' => 'use_primary_tenant_uuid',
|
|
'role_ids' => 'use_role_uuids',
|
|
'department_ids' => 'use_department_uuids',
|
|
] as $legacyKey => $errorCode) {
|
|
if (array_key_exists($legacyKey, $input)) {
|
|
$errors[$legacyKey] = [$errorCode];
|
|
}
|
|
}
|
|
if ($errors) {
|
|
return ['ok' => false, 'errors' => $errors];
|
|
}
|
|
|
|
$tenantService = directoryServicesFactory()->createTenantService();
|
|
$roleService = directoryServicesFactory()->createRoleService();
|
|
$departmentService = directoryServicesFactory()->createDepartmentService();
|
|
|
|
$normalizeUuidList = static function (mixed $raw): array {
|
|
$values = is_array($raw) ? $raw : [$raw];
|
|
$uuids = [];
|
|
foreach ($values as $value) {
|
|
$uuid = trim((string) $value);
|
|
if ($uuid !== '') {
|
|
$uuids[] = $uuid;
|
|
}
|
|
}
|
|
return array_values(array_unique($uuids));
|
|
};
|
|
|
|
if (array_key_exists('tenant_uuids', $input)) {
|
|
$tenantUuids = $normalizeUuidList($input['tenant_uuids']);
|
|
$tenantIds = [];
|
|
foreach ($tenantUuids as $tenantUuid) {
|
|
$tenant = $tenantService->findByUuid($tenantUuid);
|
|
if (!$tenant) {
|
|
$errors['tenant_uuids'][] = 'not_found';
|
|
continue;
|
|
}
|
|
$tenantId = (int) ($tenant['id'] ?? 0);
|
|
if ($tenantId > 0) {
|
|
$tenantIds[] = $tenantId;
|
|
}
|
|
}
|
|
$input['tenant_ids'] = array_values(array_unique($tenantIds));
|
|
unset($input['tenant_uuids']);
|
|
}
|
|
|
|
if (array_key_exists('primary_tenant_uuid', $input)) {
|
|
$primaryTenantUuid = trim((string) ($input['primary_tenant_uuid'] ?? ''));
|
|
if ($primaryTenantUuid === '') {
|
|
$input['primary_tenant_id'] = 0;
|
|
} else {
|
|
$primaryTenant = $tenantService->findByUuid($primaryTenantUuid);
|
|
if (!$primaryTenant) {
|
|
$errors['primary_tenant_uuid'][] = 'not_found';
|
|
} else {
|
|
$input['primary_tenant_id'] = (int) ($primaryTenant['id'] ?? 0);
|
|
}
|
|
}
|
|
unset($input['primary_tenant_uuid']);
|
|
}
|
|
|
|
if (array_key_exists('role_uuids', $input)) {
|
|
$roleUuids = $normalizeUuidList($input['role_uuids']);
|
|
$roleIds = [];
|
|
foreach ($roleUuids as $roleUuid) {
|
|
$role = $roleService->findByUuid($roleUuid);
|
|
if (!$role) {
|
|
$errors['role_uuids'][] = 'not_found';
|
|
continue;
|
|
}
|
|
$roleId = (int) ($role['id'] ?? 0);
|
|
if ($roleId > 0) {
|
|
$roleIds[] = $roleId;
|
|
}
|
|
}
|
|
$input['role_ids'] = array_values(array_unique($roleIds));
|
|
unset($input['role_uuids']);
|
|
}
|
|
|
|
if (array_key_exists('department_uuids', $input)) {
|
|
$departmentUuids = $normalizeUuidList($input['department_uuids']);
|
|
$departmentIds = [];
|
|
foreach ($departmentUuids as $departmentUuid) {
|
|
$department = $departmentService->findByUuid($departmentUuid);
|
|
if (!$department) {
|
|
$errors['department_uuids'][] = 'not_found';
|
|
continue;
|
|
}
|
|
$departmentId = (int) ($department['id'] ?? 0);
|
|
if ($departmentId > 0) {
|
|
$departmentIds[] = $departmentId;
|
|
}
|
|
}
|
|
$input['department_ids'] = array_values(array_unique($departmentIds));
|
|
unset($input['department_uuids']);
|
|
}
|
|
|
|
if ($errors) {
|
|
return ['ok' => false, 'errors' => $errors];
|
|
}
|
|
|
|
return ['ok' => true, 'input' => $input];
|
|
}
|