64 lines
2.2 KiB
PHP
64 lines
2.2 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../includes/db.php';
|
|
require_once __DIR__ . '/../includes/auth.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$action = $_GET['action'] ?? '';
|
|
|
|
switch ($action) {
|
|
case 'register':
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
if (empty($data['username']) || empty($data['password'])) {
|
|
echo json_encode(['error' => 'Missing credentials']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$stmt = $pdo->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)");
|
|
$stmt->execute([$data['username'], password_hash($data['password'], PASSWORD_DEFAULT)]);
|
|
$userId = $pdo->lastInsertId();
|
|
|
|
$_SESSION['user_id'] = $userId;
|
|
$_SESSION['username'] = $data['username'];
|
|
|
|
echo json_encode(['success' => true, 'user' => ['id' => $userId, 'username' => $data['username']]]);
|
|
} catch (PDOException $e) {
|
|
echo json_encode(['error' => 'Registration failed: ' . $e->getMessage()]);
|
|
}
|
|
break;
|
|
|
|
case 'login':
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
$stmt = $pdo->prepare("SELECT id, username, password_hash FROM users WHERE username = ?");
|
|
$stmt->execute([$data['username'] ?? '']);
|
|
$user = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($user && password_verify($data['password'] ?? '', $user['password_hash'])) {
|
|
$_SESSION['user_id'] = $user['id'];
|
|
$_SESSION['username'] = $user['username'];
|
|
echo json_encode(['success' => true, 'user' => ['id' => $user['id'], 'username' => $user['username']]]);
|
|
} else {
|
|
http_response_code(401);
|
|
echo json_encode(['error' => 'Invalid credentials']);
|
|
}
|
|
break;
|
|
|
|
case 'logout':
|
|
session_destroy();
|
|
echo json_encode(['success' => true]);
|
|
break;
|
|
|
|
case 'me':
|
|
if (isLoggedIn()) {
|
|
echo json_encode(['user' => currentUser()]);
|
|
} else {
|
|
echo json_encode(['user' => null]);
|
|
}
|
|
break;
|
|
|
|
default:
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Invalid action']);
|
|
}
|