File "add_user.php"
Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/admin/add_user.php
File
size: 4.43 B (4.43 KB bytes)
MIME-type: text/x-php
Charset: utf-8
Download Open Edit Advanced Editor Back
<?php
require_once '../includes/functions.php';
// Require Admin or SuperAdmin access
requireAdminAccess();
// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
jsonResponse(['success' => false, 'message' => 'Invalid request method'], 405);
}
// Validate CSRF token
if (!validateCSRFToken($_POST['csrf_token'] ?? '')) {
jsonResponse(['success' => false, 'message' => 'Invalid request. Please try again.'], 403);
}
// Validate required fields
$userType = sanitizeInput($_POST['userType'] ?? '');
$name = sanitizeInput($_POST['name'] ?? '');
$email = sanitizeInput($_POST['email'] ?? '');
$phone = sanitizeInput($_POST['phone'] ?? '');
$password = $_POST['password'] ?? '';
if (empty($userType) || empty($name) || empty($email) || empty($password)) {
jsonResponse(['success' => false, 'message' => 'All required fields must be filled.'], 400);
}
// Validate user type
$validTypes = ['operator', 'validator', 'admin'];
if (!in_array($userType, $validTypes)) {
jsonResponse(['success' => false, 'message' => 'Invalid user type.'], 400);
}
// Admin users can only create operators and validators, not other admins or super_admins
if ($_SESSION['user_type'] === 'admin' && in_array($userType, ['admin', 'super_admin'])) {
jsonResponse(['success' => false, 'message' => 'Admin users can only create operators and validators.'], 400);
}
// Map user type to table name (all tables are plural)
$tableMap = [
'operator' => 'operators',
'validator' => 'validators',
'admin' => 'admins'
];
$tableName = $tableMap[$userType];
if (!$tableName) {
jsonResponse(['success' => false, 'message' => 'Invalid user type.'], 400);
}
// Validate email format
if (!validateEmail($email)) {
jsonResponse(['success' => false, 'message' => 'Please enter a valid email address.'], 400);
}
// Validate password strength
if (!validatePassword($password)) {
jsonResponse(['success' => false, 'message' => 'Password must be at least 8 characters long and contain uppercase, lowercase, and number.'], 400);
}
// Validate phone if provided
if (!empty($phone) && !validatePhone($phone)) {
jsonResponse(['success' => false, 'message' => 'Please enter a valid phone number.'], 400);
}
try {
$db = Database::getInstance();
// Check if email already exists in any user table
$tables = ['auto_owners', 'passengers', 'operators', 'validators', 'admins', 'super_admins'];
foreach ($tables as $table) {
try {
$existingUser = $db->fetch("SELECT id FROM $table WHERE email = ?", [$email]);
if ($existingUser) {
error_log("Email $email already exists in table $table");
jsonResponse(['success' => false, 'message' => 'An account with this email already exists.'], 400);
}
} catch (Exception $e) {
error_log("Error checking table $table: " . $e->getMessage());
}
}
// Create the user
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$currentUserId = $_SESSION['user_id'];
error_log("Attempting to insert user into table: $tableName");
error_log("Current user ID: $currentUserId");
$sql = "INSERT INTO $tableName (name, email, password, phone, status, created_by) VALUES (?, ?, ?, ?, 'active', ?)";
error_log("SQL Query: $sql");
$result = $db->query($sql, [
$name,
$email,
$hashedPassword,
$phone,
$currentUserId
]);
if (!$result) {
throw new Exception('Database insert failed');
}
$userId = $db->lastInsertId();
error_log("User created successfully with ID: $userId");
// Log the action
logError('SuperAdmin created new ' . $userType . ' user: ' . $email . ' (ID: ' . $userId . ')');
jsonResponse([
'success' => true,
'message' => ucfirst($userType) . ' created successfully!',
'user' => [
'id' => $userId,
'name' => $name,
'email' => $email,
'type' => $userType
]
]);
} catch (Exception $e) {
error_log('Backend user creation error: ' . $e->getMessage());
error_log('Stack trace: ' . $e->getTraceAsString());
logError('Backend user creation error: ' . $e->getMessage());
jsonResponse(['success' => false, 'message' => 'Failed to create user: ' . $e->getMessage()], 500);
}