Files
musadaq-saas/app/modules_app/users/create.php
2026-05-03 22:51:59 +03:00

69 lines
2.0 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'],
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
// 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([
$decoded['tenant_id'],
$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);
}