Change redirect_uri to app root (without /auth.php) to match what's registered in Azure portal. Use relative URLs for auth fetch and reload on success instead of computed absolute paths. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
353 lines
12 KiB
PHP
353 lines
12 KiB
PHP
<?php
|
|
/**
|
|
* Authentication Middleware
|
|
* Handles SSO authentication with local development mode support
|
|
* Based on Ferrero naming convention authentication pattern
|
|
*/
|
|
|
|
class AuthMiddleware {
|
|
private $ssoEnabled;
|
|
private $tenantId;
|
|
private $clientId;
|
|
private $redirectUri;
|
|
private $localUser;
|
|
private $validator;
|
|
|
|
public function __construct() {
|
|
$config = require __DIR__ . '/config.php';
|
|
|
|
// Load SSO configuration
|
|
$this->ssoEnabled = $config['sso']['enabled'] ?? false;
|
|
$this->tenantId = $config['sso']['tenant_id'] ?? '';
|
|
$this->clientId = $config['sso']['client_id'] ?? '';
|
|
$this->redirectUri = $config['sso']['redirect_uri'] ?? '';
|
|
$this->localUser = $config['sso']['local_user'] ?? [
|
|
'name' => 'Local User',
|
|
'email' => 'local@example.com',
|
|
'role' => 'user'
|
|
];
|
|
|
|
// Only load JWT validator if SSO is enabled
|
|
if ($this->ssoEnabled && file_exists(__DIR__ . '/JWTValidator.php')) {
|
|
require_once __DIR__ . '/JWTValidator.php';
|
|
$this->validator = new JWTValidator($this->tenantId, $this->clientId);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if SSO is enabled
|
|
*/
|
|
public function isSSOEnabled() {
|
|
return $this->ssoEnabled;
|
|
}
|
|
|
|
/**
|
|
* Check if user is authenticated
|
|
* Returns array with 'authenticated' status and 'user' info or 'error'
|
|
*/
|
|
public function isAuthenticated() {
|
|
// If SSO is disabled, return mock user for local development
|
|
if (!$this->ssoEnabled) {
|
|
return [
|
|
'authenticated' => true,
|
|
'user' => [
|
|
'name' => $this->localUser['name'],
|
|
'email' => $this->localUser['email'],
|
|
'role' => $this->localUser['role'] ?? 'admin'
|
|
]
|
|
];
|
|
}
|
|
|
|
// SSO enabled - validate token from cookie
|
|
if (!isset($_COOKIE['auth_token'])) {
|
|
return [
|
|
'authenticated' => false,
|
|
'error' => 'No authentication token found'
|
|
];
|
|
}
|
|
|
|
$token = $_COOKIE['auth_token'];
|
|
|
|
try {
|
|
// Validate JWT token
|
|
$result = $this->validator->validate($token);
|
|
|
|
if ($result['valid']) {
|
|
$email = strtolower($result['claims']['preferred_username'] ??
|
|
$result['claims']['upn'] ?? 'Unknown');
|
|
require_once __DIR__ . '/UserRoleManager.php';
|
|
$roleManager = new UserRoleManager();
|
|
$role = $roleManager->getRole($email);
|
|
|
|
return [
|
|
'authenticated' => true,
|
|
'user' => [
|
|
'name' => $result['claims']['name'] ?? 'Unknown',
|
|
'email' => $email,
|
|
'role' => $role
|
|
]
|
|
];
|
|
} else {
|
|
return [
|
|
'authenticated' => false,
|
|
'error' => $result['error'] ?? 'Invalid token'
|
|
];
|
|
}
|
|
} catch (Exception $e) {
|
|
return [
|
|
'authenticated' => false,
|
|
'error' => 'Token validation failed: ' . $e->getMessage()
|
|
];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Require authentication - redirects to login if not authenticated
|
|
* Returns user info array if authenticated
|
|
*/
|
|
public function requireAuth() {
|
|
// If SSO is disabled, return mock user immediately
|
|
if (!$this->ssoEnabled) {
|
|
return [
|
|
'name' => $this->localUser['name'],
|
|
'email' => $this->localUser['email'],
|
|
'role' => $this->localUser['role'] ?? 'admin'
|
|
];
|
|
}
|
|
|
|
// Check authentication status
|
|
$auth = $this->isAuthenticated();
|
|
|
|
if (!$auth['authenticated']) {
|
|
$this->handleUnauthorized($auth['error'] ?? 'Authentication required');
|
|
exit;
|
|
}
|
|
|
|
return $auth['user'];
|
|
}
|
|
|
|
/**
|
|
* Require admin role - shows 403 if authenticated but not admin
|
|
* Returns user info array if authenticated as admin
|
|
*/
|
|
public function requireAdmin() {
|
|
$user = $this->requireAuth();
|
|
|
|
if (($user['role'] ?? 'user') !== 'admin') {
|
|
http_response_code(403);
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Access Denied</title>
|
|
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap" rel="stylesheet">
|
|
<style>
|
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
body { font-family: 'Montserrat', sans-serif; background-color: #000; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
|
|
.box { background: #fff; padding: 40px; border-radius: 10px; box-shadow: 0 4px 20px rgba(255,196,7,0.3); max-width: 400px; width: 100%; text-align: center; }
|
|
h1 { color: #000; margin-bottom: 16px; font-size: 28px; }
|
|
p { color: #555; margin-bottom: 24px; }
|
|
a { display: inline-block; padding: 12px 28px; background: #FFC407; color: #000; border-radius: 5px; font-weight: 700; text-decoration: none; }
|
|
a:hover { background: #000; color: #FFC407; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="box">
|
|
<h1>Access Denied</h1>
|
|
<p>You need admin privileges to view this page.</p>
|
|
<a href="index.php">Go Back</a>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
<?php
|
|
exit;
|
|
}
|
|
|
|
return $user;
|
|
}
|
|
|
|
/**
|
|
* Handle unauthorized access
|
|
*/
|
|
private function handleUnauthorized($error) {
|
|
// Check if this is an AJAX request
|
|
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
|
|
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
|
|
|
|
if ($isAjax) {
|
|
// Return JSON for AJAX requests
|
|
http_response_code(401);
|
|
header('Content-Type: application/json');
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Unauthorized',
|
|
'message' => $error,
|
|
'requireAuth' => true
|
|
]);
|
|
} else {
|
|
// Show login page for regular requests
|
|
$this->showLoginPage($error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Display login page
|
|
*/
|
|
private function showLoginPage($error = '') {
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Login Required</title>
|
|
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap" rel="stylesheet">
|
|
<style>
|
|
* {
|
|
margin: 0;
|
|
padding: 0;
|
|
box-sizing: border-box;
|
|
}
|
|
body {
|
|
font-family: 'Montserrat', sans-serif;
|
|
background-color: #000000;
|
|
display: flex;
|
|
justify-content: center;
|
|
align-items: center;
|
|
min-height: 100vh;
|
|
padding: 20px;
|
|
}
|
|
.login-container {
|
|
background-color: #ffffff;
|
|
padding: 40px;
|
|
border-radius: 10px;
|
|
box-shadow: 0 4px 6px rgba(255, 196, 7, 0.3);
|
|
max-width: 400px;
|
|
width: 100%;
|
|
text-align: center;
|
|
}
|
|
h1 {
|
|
color: #000000;
|
|
margin-bottom: 20px;
|
|
font-weight: 700;
|
|
}
|
|
.error {
|
|
background-color: #ff4444;
|
|
color: white;
|
|
padding: 12px;
|
|
border-radius: 5px;
|
|
margin-bottom: 20px;
|
|
font-size: 14px;
|
|
}
|
|
.login-btn {
|
|
width: 100%;
|
|
padding: 14px;
|
|
background-color: #FFC407;
|
|
color: #000000;
|
|
border: none;
|
|
border-radius: 5px;
|
|
font-family: 'Montserrat', sans-serif;
|
|
font-size: 16px;
|
|
font-weight: 700;
|
|
cursor: pointer;
|
|
transition: all 0.3s ease;
|
|
}
|
|
.login-btn:hover {
|
|
background-color: #000000;
|
|
color: #FFC407;
|
|
transform: translateY(-2px);
|
|
}
|
|
</style>
|
|
<script src="https://alcdn.msauth.net/browser/2.15.0/js/msal-browser.min.js"></script>
|
|
</head>
|
|
<body>
|
|
<div class="login-container">
|
|
<h1>Authentication Required</h1>
|
|
<?php if ($error): ?>
|
|
<div class="error"><?php echo htmlspecialchars($error); ?></div>
|
|
<?php endif; ?>
|
|
<button class="login-btn" onclick="signIn()">Sign In with Microsoft</button>
|
|
</div>
|
|
|
|
<script>
|
|
const msalConfig = {
|
|
auth: {
|
|
clientId: '<?php echo $this->clientId; ?>',
|
|
authority: 'https://login.microsoftonline.com/<?php echo $this->tenantId; ?>',
|
|
redirectUri: '<?php echo $this->redirectUri; ?>'
|
|
}
|
|
};
|
|
|
|
const msalInstance = new msal.PublicClientApplication(msalConfig);
|
|
|
|
async function signIn() {
|
|
try {
|
|
const loginResponse = await msalInstance.loginPopup({
|
|
scopes: ['openid', 'profile', 'email']
|
|
});
|
|
|
|
// Send token to server
|
|
const response = await fetch('auth.php?action=login', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json'
|
|
},
|
|
body: JSON.stringify({
|
|
token: loginResponse.idToken
|
|
})
|
|
});
|
|
|
|
const result = await response.json();
|
|
|
|
if (result.success) {
|
|
window.location.reload();
|
|
} else {
|
|
alert('Login failed: ' + result.message);
|
|
}
|
|
} catch (error) {
|
|
console.error('Login error:', error);
|
|
alert('Login failed. Please try again.');
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
</html>
|
|
<?php
|
|
}
|
|
|
|
/**
|
|
* Set authentication token in cookie
|
|
*/
|
|
public function setAuthToken($token) {
|
|
$cookieOptions = [
|
|
'expires' => time() + (24 * 60 * 60), // 24 hours
|
|
'path' => '/',
|
|
'domain' => '',
|
|
'secure' => isset($_SERVER['HTTPS']),
|
|
'httponly' => true,
|
|
'samesite' => 'Lax'
|
|
];
|
|
|
|
setcookie('auth_token', $token, $cookieOptions);
|
|
}
|
|
|
|
/**
|
|
* Clear authentication token
|
|
*/
|
|
public function clearAuthToken() {
|
|
if (isset($_COOKIE['auth_token'])) {
|
|
setcookie('auth_token', '', time() - 3600, '/');
|
|
unset($_COOKIE['auth_token']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get current user info (or null if not authenticated)
|
|
*/
|
|
public function getCurrentUser() {
|
|
$auth = $this->isAuthenticated();
|
|
return $auth['authenticated'] ? $auth['user'] : null;
|
|
}
|
|
}
|