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 = '') { ?>