loreal-global-kickoff/AuthMiddleware.php
DJP dbf7090d09 Initial commit: L'Oréal Box Asset Submission Form
- Set up PHP application with Composer and JWT library
- Implemented SSO authentication with local dev mode
- Created Box API service for folder validation
- Built two-column form interface (form + preview)
- Added real-time Box ID validation with AJAX
- Integrated webhook submission with status response
- Auto-populate Master Campaign Number from Box folder hierarchy
- Responsive design with Montserrat font and black/yellow theme

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 14:43:36 -05:00

300 lines
9.7 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 $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->localUser = $config['sso']['local_user'] ?? [
'name' => 'Local User',
'email' => 'local@example.com'
];
// 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']
]
];
}
// 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']) {
return [
'authenticated' => true,
'user' => [
'name' => $result['claims']['name'] ?? 'Unknown',
'email' => $result['claims']['preferred_username'] ??
$result['claims']['upn'] ?? 'Unknown'
]
];
} 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']
];
}
// Check authentication status
$auth = $this->isAuthenticated();
if (!$auth['authenticated']) {
$this->handleUnauthorized($auth['error'] ?? 'Authentication required');
exit;
}
return $auth['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: window.location.origin + '/auth.php'
}
};
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.href = '/';
} 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;
}
}