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); ?>