Update: 2026-05-03 21:58:11
This commit is contained in:
56
app/modules_app/users/create.php
Normal file
56
app/modules_app/users/create.php
Normal file
@@ -0,0 +1,56 @@
|
||||
<?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 (name, email, email_hash, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)");
|
||||
$stmt->execute([
|
||||
$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);
|
||||
}
|
||||
Reference in New Issue
Block a user