validator = new JWTValidator($this->tenantId, $this->clientId); } /** * Check if user is authenticated */ public function isAuthenticated() { $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() { $auth = $this->isAuthenticated(); if (!$auth['authenticated']) { $this->handleUnauthorized($auth['error']); exit; } return $auth['user']; } /** * Set authentication token in httpOnly cookie */ public function setAuthToken($token) { $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) { ?> Login Required - Markdown to HTML Converter

Authentication Required

Please sign in with your Microsoft account to access the Markdown converter.