ferrero-naming-tool-nv/public-v2/AuthMiddleware.php
nickviljoen 58a1a8fdb5 Add project source files and documentation
Includes backend API, public-v2 frontend, database migrations,
Composer config, and deployment/implementation docs.
Config files with credentials are excluded via .gitignore.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 19:19:12 +02:00

305 lines
10 KiB
PHP

<?php
require_once __DIR__ . '/../config.php';
class AuthMiddleware {
private $validator;
private $tenantId;
private $clientId;
private $ssoEnabled;
public function __construct() {
$config = require __DIR__ . '/../config.php';
$this->ssoEnabled = $config['sso']['enabled'] ?? false;
$this->tenantId = $config['sso']['tenant_id'] ?? '';
$this->clientId = $config['sso']['client_id'] ?? '';
if ($this->ssoEnabled) {
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
*/
public function isAuthenticated() {
// If SSO is disabled, return authenticated with mock user
if (!$this->ssoEnabled) {
return [
'authenticated' => true,
'user' => [
'name' => 'Local Developer',
'preferred_username' => 'dev@localhost'
]
];
}
$token = $this->getTokenFromCookie();
if (!$token) {
return ['authenticated' => false, 'error' => 'No authentication token found'];
}
$validation = $this->validator->validateToken($token);
if (!$validation['valid']) {
return ['authenticated' => false, 'error' => $validation['error']];
}
return ['authenticated' => true, 'user' => $validation['payload']];
}
/**
* Require authentication for current request
*/
public function requireAuth() {
// If SSO is disabled, return mock user
if (!$this->ssoEnabled) {
return [
'name' => 'Local Developer',
'preferred_username' => 'dev@localhost'
];
}
$auth = $this->isAuthenticated();
if (!$auth['authenticated']) {
$this->handleUnauthorized($auth['error']);
exit;
}
return $auth['user'];
}
/**
* Set authentication token in httpOnly cookie
*/
public function setAuthToken($token) {
if (!$this->ssoEnabled) {
return ['success' => false, 'error' => 'SSO is disabled'];
}
$validation = $this->validator->validateToken($token);
if (!$validation['valid']) {
return ['success' => false, 'error' => $validation['error']];
}
// Set httpOnly cookie with security options
$cookieOptions = [
'expires' => time() + (24 * 60 * 60), // 24 hours
'path' => '/',
'domain' => '',
'secure' => isset($_SERVER['HTTPS']), // Only over HTTPS in production
'httponly' => true,
'samesite' => 'Lax'
];
setcookie('auth_token', $token, $cookieOptions);
return ['success' => true, 'user' => $validation['payload']];
}
/**
* Clear authentication token
*/
public function clearAuthToken() {
setcookie('auth_token', '', [
'expires' => time() - 3600,
'path' => '/',
'httponly' => true
]);
}
/**
* Get token from httpOnly cookie
*/
private function getTokenFromCookie() {
return isset($_COOKIE['auth_token']) ? $_COOKIE['auth_token'] : null;
}
/**
* Handle unauthorized access
*/
private function handleUnauthorized($error) {
if ($this->isAjaxRequest()) {
header('Content-Type: application/json');
http_response_code(401);
echo json_encode([
'error' => 'Authentication required',
'message' => $error,
'requiresAuth' => true
]);
} else {
// For page requests, show login interface
$this->showLoginPage($error);
}
}
/**
* Check if request is AJAX
*/
private function isAjaxRequest() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
}
/**
* Show login page for unauthenticated users
*/
private function showLoginPage($error = null) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Required - Ferrero Naming Convention Tool</title>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<script src="https://alcdn.msauth.net/browser/2.15.0/js/msal-browser.min.js" crossorigin="anonymous"></script>
<style>
:root {
--primary: #d32f2f;
--primary-dark: #b71c1c;
--text-primary: #333;
--text-secondary: #666;
}
body {
font-family: 'Montserrat', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #FBF8F3 0%, #F5F0E8 100%);
margin: 0;
padding: 0;
}
.login-container {
max-width: 500px;
margin: 100px auto;
padding: 40px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
text-align: center;
}
.login-logo {
font-size: 48px;
margin-bottom: 20px;
color: var(--primary);
}
.login-title {
font-size: 24px;
font-weight: 600;
margin-bottom: 10px;
color: var(--text-primary);
}
.login-subtitle {
color: var(--text-secondary);
margin-bottom: 30px;
}
.login-error {
background: #fee;
border: 1px solid #fcc;
color: #c33;
padding: 12px;
border-radius: 4px;
margin-bottom: 20px;
font-size: 14px;
}
.btn-login {
background: #0078d4;
color: white;
border: none;
padding: 14px 32px;
font-size: 16px;
font-weight: 600;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
display: inline-block;
}
.btn-login:hover {
background: #106ebe;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
.btn-login:active {
transform: translateY(0);
}
</style>
</head>
<body>
<div class="login-container">
<div class="login-logo">🏷️</div>
<h1 class="login-title">Ferrero Naming Convention Tool</h1>
<p class="login-subtitle">Please sign in with your Microsoft account to continue</p>
<button class="btn-login" onclick="signIn()">
<span style="display: inline-block; margin-right: 8px;">&#x1F512;</span>
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: "https://ai-sandbox.oliver.solutions/ferreo-naming-tool/public-v2/"
},
cache: {
cacheLocation: "sessionStorage",
storeAuthStateInCookie: true,
}
};
const loginRequest = {
scopes: ["openid", "profile", "email"],
prompt: "select_account"
};
const myMSALObj = new msal.PublicClientApplication(msalConfig);
function signIn() {
myMSALObj.loginPopup(loginRequest)
.then(loginResponse => {
// Send token to server for validation and cookie setting
fetch('auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'login',
idToken: loginResponse.idToken,
accessToken: loginResponse.accessToken
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.reload();
} else {
alert('Authentication failed: ' + data.error);
}
})
.catch(error => {
console.error('Authentication error:', error);
alert('Authentication failed. Please try again.');
});
})
.catch(error => {
console.error("Login failed:", error);
alert('Login failed: ' + error.message);
});
}
</script>
</body>
</html>
<?php
}
}