Files
musadaq-saas/app/modules_app/users/create.php
2026-05-04 01:33:55 +03:00

80 lines
2.3 KiB
PHP

<?php
/**
* Create User Endpoint (with Encryption)
*/
use App\Core\Database;
use App\Core\Encryption;
use App\Core\Validator;
use App\Middleware\AuthMiddleware;
// 1. Auth Check (Only super_admin or admin can create users)
$decoded = AuthMiddleware::check();
if ($decoded['role'] !== 'super_admin' && $decoded['role'] !== 'admin') {
json_error('Unauthorized', 403);
}
$data = input();
// 1. Role Authorization check (Prevent Role Escalation)
$allowedRoles = match($decoded['role']) {
'super_admin' => ['super_admin', 'admin', 'accountant', 'employee', 'viewer'],
'admin' => ['accountant', 'employee', 'viewer'], // Cannot create other admins
default => []
};
if (!in_array($data['role'] ?? '', $allowedRoles, true)) {
json_error('غير مصرح لك بإنشاء مستخدم بهذا الدور', 403);
}
// 2. Validation
$errors = Validator::validate($data, [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'role' => 'required'
]);
if ($errors) {
json_error('Validation Failed', 422, $errors);
}
$db = Database::getInstance();
// 3. Encrypt sensitive data
$encryptedName = Encryption::encrypt($data['name']);
$encryptedEmail = Encryption::encrypt($data['email']);
$emailHash = hash('sha256', strtolower($data['email'])); // For fast lookup during login
// 3. Determine Tenant ID
$tenantId = null;
if ($decoded['role'] === 'super_admin') {
if (empty($data['tenant_id'])) {
json_error('يجب اختيار المكتب المحاسبي', 422);
}
$tenantId = $data['tenant_id'];
} else {
$tenantId = $decoded['tenant_id'];
}
// 4. Save to Database
try {
$stmt = $db->prepare("INSERT INTO users (tenant_id, name, email, email_hash, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([
$tenantId,
$encryptedName,
$encryptedEmail,
$emailHash,
password_hash($data['password'], PASSWORD_DEFAULT),
$data['role'],
date('Y-m-d H:i:s')
]);
json_success(null, 'تم إضافة المستخدم بنجاح');
} catch (\Exception $e) {
if (str_contains($e->getMessage(), 'Duplicate entry')) {
json_error('البريد الإلكتروني مسجل مسبقاً', 409);
}
json_error('حدث خطأ أثناء حفظ البيانات', 500);
}