89 lines
No EOL
2.3 KiB
PHP
89 lines
No EOL
2.3 KiB
PHP
<?php
|
|
|
|
require_once 'config.php';
|
|
require_once 'AuthMiddleware.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$auth = new AuthMiddleware();
|
|
|
|
// Handle different authentication actions
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$action = $input['action'] ?? $_POST['action'] ?? $_GET['action'] ?? '';
|
|
|
|
switch ($action) {
|
|
case 'login':
|
|
handleLogin($auth, $input);
|
|
break;
|
|
|
|
case 'logout':
|
|
handleLogout($auth);
|
|
break;
|
|
|
|
case 'status':
|
|
handleStatus($auth);
|
|
break;
|
|
|
|
default:
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Invalid action']);
|
|
break;
|
|
}
|
|
|
|
function handleLogin($auth, $input) {
|
|
// Prefer ID token for validation, fallback to access token
|
|
$token = $input['idToken'] ?? $input['accessToken'] ?? null;
|
|
|
|
if (!$token) {
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Authentication token is required']);
|
|
return;
|
|
}
|
|
|
|
$result = $auth->setAuthToken($token);
|
|
|
|
if ($result['success']) {
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Authentication successful',
|
|
'user' => [
|
|
'name' => $result['user']['name'] ?? 'Unknown',
|
|
'email' => $result['user']['preferred_username'] ?? $result['user']['upn'] ?? 'Unknown'
|
|
]
|
|
]);
|
|
} else {
|
|
http_response_code(401);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => $result['error']
|
|
]);
|
|
}
|
|
}
|
|
|
|
function handleLogout($auth) {
|
|
$auth->clearAuthToken();
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Logged out successfully'
|
|
]);
|
|
}
|
|
|
|
function handleStatus($auth) {
|
|
$authStatus = $auth->isAuthenticated();
|
|
|
|
if ($authStatus['authenticated']) {
|
|
echo json_encode([
|
|
'authenticated' => true,
|
|
'user' => [
|
|
'name' => $authStatus['user']['name'] ?? 'Unknown',
|
|
'email' => $authStatus['user']['preferred_username'] ?? $authStatus['user']['upn'] ?? 'Unknown'
|
|
]
|
|
]);
|
|
} else {
|
|
http_response_code(401);
|
|
echo json_encode([
|
|
'authenticated' => false,
|
|
'error' => $authStatus['error']
|
|
]);
|
|
}
|
|
} |