34705-vm/api/update_user_role.php
Flatlogic Bot 2587a17d37 basic2
2025-10-06 00:19:27 +00:00

55 lines
1.7 KiB
PHP

<?php
require_once __DIR__ . '/../db/config.php';
session_start();
header('Content-Type: application/json');
// Admin-only endpoint
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Forbidden: Admins only.']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
if (!$data || !isset($data['user_id']) || !isset($data['role'])) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid input. User ID and role are required.']);
exit;
}
$userIdToUpdate = $data['user_id'];
$newRole = $data['role'];
$allowedRoles = ['regular', 'sports_analyst', 'sports_bettor', 'admin'];
if (!in_array($newRole, $allowedRoles)) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid role specified.']);
exit;
}
// Prevent admin from accidentally changing their own role and getting locked out
if ($userIdToUpdate == $_SESSION['user_id'] && $newRole !== 'admin') {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Admins cannot remove their own admin status.']);
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare('UPDATE users SET role = ? WHERE id = ?');
$stmt->execute([$newRole, $userIdToUpdate]);
if ($stmt->rowCount() > 0) {
echo json_encode(['status' => 'success', 'message' => 'User role updated successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'User not found or role is already set.']);
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}