86 lines
2.5 KiB
PHP
86 lines
2.5 KiB
PHP
<?php
|
|
/**
|
|
* Token Validation Endpoint
|
|
* Receives access token from client-side MSAL.js and creates PHP session
|
|
*/
|
|
require_once 'config.php';
|
|
|
|
// Only accept POST requests
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['success' => false, 'error' => 'Method not allowed']);
|
|
exit;
|
|
}
|
|
|
|
// Get JSON payload
|
|
$json = file_get_contents('php://input');
|
|
$data = json_decode($json, true);
|
|
|
|
if (!isset($data['accessToken'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'error' => 'Access token required']);
|
|
exit;
|
|
}
|
|
|
|
$accessToken = $data['accessToken'];
|
|
|
|
try {
|
|
// Validate token by calling Microsoft Graph API
|
|
// If the token is valid, Graph API will return user info
|
|
// If invalid, it will fail
|
|
$ch = curl_init('https://graph.microsoft.com/v1.0/me');
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
|
'Authorization: Bearer ' . $accessToken,
|
|
'Content-Type: application/json'
|
|
]);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
|
|
if ($httpCode !== 200) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'error' => 'Invalid token']);
|
|
exit;
|
|
}
|
|
|
|
// Parse user data
|
|
$userData = json_decode($response, true);
|
|
|
|
if (!$userData || !isset($userData['id'])) {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'error' => 'Failed to retrieve user information']);
|
|
exit;
|
|
}
|
|
|
|
// Start session and store user information
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
$_SESSION['authenticated'] = true;
|
|
$_SESSION['user_id'] = $userData['id'];
|
|
$_SESSION['user_name'] = $userData['displayName'] ?? $userData['userPrincipalName'];
|
|
$_SESSION['user_email'] = $userData['userPrincipalName'] ?? $userData['mail'];
|
|
$_SESSION['access_token'] = $accessToken;
|
|
$_SESSION['last_activity'] = time();
|
|
$_SESSION['user_files'] = [];
|
|
|
|
// Regenerate session ID for security
|
|
session_regenerate_id(true);
|
|
|
|
// Return success
|
|
echo json_encode([
|
|
'success' => true,
|
|
'user' => [
|
|
'name' => $_SESSION['user_name'],
|
|
'email' => $_SESSION['user_email']
|
|
]
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
|
|
}
|