Files
coursehub/api/auth.php
T
Harwinder Sekhon 3ae6c1ae2e CourseHub: AJAX video course player (PHP + MySQL + Bootstrap + Plyr)
Scans nested course folders for mp4s, tracks per-user resume position
and per-folder progress. SPA frontend with hash routing over a JSON API;
range-request streaming via stream.php.
2026-07-11 10:25:35 -04:00

65 lines
1.9 KiB
PHP

<?php
// GET api/auth.php -> {logged_in, username}
// POST api/auth.php {action, username?, password?}
// action: login | register | logout
require_once __DIR__ . '/../includes/auth.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
echo json_encode([
'logged_in' => currentUserId() !== null,
'username' => currentUsername(),
'allow_registration' => ALLOW_REGISTRATION,
]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true) ?: [];
$action = $data['action'] ?? '';
$username = trim($data['username'] ?? '');
$password = $data['password'] ?? '';
switch ($action) {
case 'login':
if (attemptLogin($username, $password)) {
echo json_encode(['ok' => true, 'username' => currentUsername()]);
} else {
http_response_code(401);
echo json_encode(['error' => 'Invalid username or password.']);
}
break;
case 'register':
if (!ALLOW_REGISTRATION) {
http_response_code(403);
echo json_encode(['error' => 'Registration is disabled.']);
break;
}
$result = registerUser($username, $password);
if ($result === true) {
attemptLogin($username, $password);
echo json_encode(['ok' => true, 'username' => currentUsername()]);
} else {
http_response_code(422);
echo json_encode(['error' => $result]);
}
break;
case 'logout':
$_SESSION = [];
session_destroy();
echo json_encode(['ok' => true]);
break;
default:
http_response_code(400);
echo json_encode(['error' => 'Unknown action']);
}