58 lines
1.6 KiB
PHP
58 lines
1.6 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();
|
|
|
|
// 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);
|
|
}
|