mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-16 11:23:10 +02:00
Saml fix (#5651)
# Description of Changes When password login is disabled UI changes to have central style SSO button <img width="2057" height="1369" alt="image" src="https://github.com/user-attachments/assets/8f65f778-0809-4c54-a9c4-acf3a67cfa63" /> Auto SSO login functionality Massively increases auth debugging visibility: verbose console logging in ErrorBoundary, AuthProvider, Landing, AuthCallback. Improves OAuth/SAML testability: adds Keycloak docker-compose setups + realm JSON exports + start/validate scripts for OAuth and SAML environments. Hardens license upload path handling: better logs + safer directory traversal protection by normalizing absolute paths before startsWith check. UI polish for SSO-only login: new “single provider” centered layout + updated button styles (pill buttons, variants, icon wrapper, arrow). <!-- Please provide a summary of the changes, including: - What was changed - Why the change was made - Any challenges encountered Closes #(issue_number) --> --- ## Checklist ### General - [ ] I have read the [Contribution Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md) - [ ] I have read the [Stirling-PDF Developer Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md) (if applicable) - [ ] I have read the [How to add new languages to Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md) (if applicable) - [ ] I have performed a self-review of my own code - [ ] My changes generate no new warnings ### Documentation - [ ] I have updated relevant docs on [Stirling-PDF's doc repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/) (if functionality has heavily changed) - [ ] I have read the section [Add New Translation Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags) (for new translation tags only) ### Translations (if applicable) - [ ] I ran [`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md) ### UI Changes (if applicable) - [ ] Screenshots or videos demonstrating the UI changes are attached (e.g., as comments or direct attachments in the PR) ### Testing (if applicable) - [ ] I have tested my changes locally. Refer to the [Testing Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing) for more details.
This commit is contained in:
@@ -36,6 +36,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<AuthError | null>(null);
|
||||
|
||||
// Debug: Track state transitions
|
||||
useEffect(() => {
|
||||
console.log('[Auth] State changed:', {
|
||||
loading,
|
||||
hasSession: !!session,
|
||||
hasError: !!error,
|
||||
userId: session?.user?.id,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}, [loading, session, error]);
|
||||
|
||||
/**
|
||||
* Refresh current session
|
||||
*/
|
||||
@@ -92,10 +103,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
*/
|
||||
useEffect(() => {
|
||||
let mounted = true;
|
||||
const mountId = Math.random().toString(36).substring(7);
|
||||
console.log(`[Auth:${mountId}] 🔵 AuthProvider mounted`);
|
||||
|
||||
const initializeAuth = async () => {
|
||||
try {
|
||||
console.debug('[Auth] Initializing auth...');
|
||||
console.debug(`[Auth:${mountId}] Initializing auth...`);
|
||||
// Clear any platform-specific cached auth on login page init.
|
||||
if (typeof window !== 'undefined' && window.location.pathname.startsWith('/login')) {
|
||||
await clearPlatformAuthOnLoginInit();
|
||||
@@ -134,7 +147,13 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
// Listen for jwt-available event (triggered by desktop auth or other sources)
|
||||
const handleJwtAvailable = () => {
|
||||
console.debug('[Auth] JWT available event received, refreshing session');
|
||||
console.log(`[Auth:${mountId}] ════════════════════════════════════`);
|
||||
console.log(`[Auth:${mountId}] 🔄 JWT available event received`);
|
||||
console.log(`[Auth:${mountId}] Current state: loading=${loading}, hasSession=${!!session}`);
|
||||
console.log(`[Auth:${mountId}] Setting loading=true to stabilize auth state`);
|
||||
setLoading(true); // Prevent unstable renders during auth state transition
|
||||
setError(null);
|
||||
console.log(`[Auth:${mountId}] Refreshing session...`);
|
||||
void initializeAuth();
|
||||
};
|
||||
|
||||
@@ -143,38 +162,43 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
// Subscribe to auth state changes
|
||||
const { data: { subscription } } = springAuth.onAuthStateChange(
|
||||
async (event: AuthChangeEvent, newSession: Session | null) => {
|
||||
if (!mounted) return;
|
||||
if (!mounted) {
|
||||
console.log(`[Auth:${mountId}] ⚠️ Auth state change ignored (unmounted): ${event}`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.debug('[Auth] Auth state change:', {
|
||||
event,
|
||||
hasSession: !!newSession,
|
||||
userId: newSession?.user?.id,
|
||||
email: newSession?.user?.email,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
console.log(`[Auth:${mountId}] ════════════════════════════════════`);
|
||||
console.log(`[Auth:${mountId}] 📢 Auth state change event: ${event}`);
|
||||
console.log(`[Auth:${mountId}] Has session: ${!!newSession}`);
|
||||
console.log(`[Auth:${mountId}] User: ${newSession?.user?.email || 'none'}`);
|
||||
console.log(`[Auth:${mountId}] Timestamp: ${new Date().toISOString()}`);
|
||||
|
||||
// Schedule state update
|
||||
setTimeout(() => {
|
||||
if (mounted) {
|
||||
console.log(`[Auth:${mountId}] Applying session update (event: ${event})`);
|
||||
setSession(newSession);
|
||||
setError(null);
|
||||
|
||||
// Handle specific events
|
||||
if (event === 'SIGNED_OUT') {
|
||||
console.debug('[Auth] User signed out, clearing session');
|
||||
console.log(`[Auth:${mountId}] ✓ User signed out, session cleared`);
|
||||
} else if (event === 'SIGNED_IN') {
|
||||
console.debug('[Auth] User signed in successfully');
|
||||
console.log(`[Auth:${mountId}] ✓ User signed in successfully`);
|
||||
} else if (event === 'TOKEN_REFRESHED') {
|
||||
console.debug('[Auth] Token refreshed');
|
||||
console.log(`[Auth:${mountId}] ✓ Token refreshed`);
|
||||
} else if (event === 'USER_UPDATED') {
|
||||
console.debug('[Auth] User updated');
|
||||
console.log(`[Auth:${mountId}] ✓ User updated`);
|
||||
}
|
||||
} else {
|
||||
console.log(`[Auth:${mountId}] ⚠️ Session update skipped (unmounted during timeout)`);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
console.log(`[Auth:${mountId}] 🔴 AuthProvider unmounting`);
|
||||
mounted = false;
|
||||
window.removeEventListener('jwt-available', handleJwtAvailable);
|
||||
subscription.unsubscribe();
|
||||
|
||||
@@ -312,6 +312,9 @@ class SpringAuthClient {
|
||||
*/
|
||||
async signOut(): Promise<{ error: AuthError | null }> {
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.sessionStorage.setItem('stirling_sso_auto_login_logged_out', '1');
|
||||
}
|
||||
const response = await apiClient.post('/api/v1/auth/logout', null, {
|
||||
headers: {
|
||||
'X-XSRF-TOKEN': this.getCsrfToken() || '',
|
||||
|
||||
@@ -12,6 +12,9 @@ interface AccountLogoutDeps {
|
||||
export function useAccountLogout() {
|
||||
return async ({ signOut, redirectToLogin }: AccountLogoutDeps): Promise<void> => {
|
||||
try {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.sessionStorage.setItem('stirling_sso_auto_login_logged_out', '1');
|
||||
}
|
||||
await signOut();
|
||||
} finally {
|
||||
redirectToLogin();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { springAuth } from '@app/auth/springAuthClient';
|
||||
import { handleAuthCallbackSuccess } from '@app/extensions/authCallback';
|
||||
@@ -13,11 +13,46 @@ import styles from '@app/routes/AuthCallback.module.css';
|
||||
*/
|
||||
export default function AuthCallback() {
|
||||
const navigate = useNavigate();
|
||||
const processingRef = useRef(false);
|
||||
|
||||
// Log component lifecycle
|
||||
useEffect(() => {
|
||||
const mountId = Math.random().toString(36).substring(7);
|
||||
console.log(`[AuthCallback:${mountId}] 🔵 Component mounted`);
|
||||
return () => {
|
||||
console.log(`[AuthCallback:${mountId}] 🔴 Component unmounting`);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCallback = async () => {
|
||||
const startTime = performance.now();
|
||||
const executionId = Math.random().toString(36).substring(7);
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] ════════════════════════════════════`);
|
||||
console.log(`[AuthCallback:${executionId}] Starting authentication callback`);
|
||||
console.log(`[AuthCallback:${executionId}] URL: ${window.location.href}`);
|
||||
console.log(`[AuthCallback:${executionId}] Hash: ${window.location.hash}`);
|
||||
|
||||
if (typeof window !== 'undefined' && window.sessionStorage.getItem('stirling_sso_auto_login_logged_out') === '1') {
|
||||
console.warn(`[AuthCallback:${executionId}] ⚠️ Logout block active, skipping token processing`);
|
||||
navigate('/login', {
|
||||
replace: true,
|
||||
state: { error: 'You have been signed out. Please sign in again.' }
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Prevent double execution (React 18 Strict Mode + navigate dependency)
|
||||
if (processingRef.current) {
|
||||
console.warn(`[AuthCallback:${executionId}] ⚠️ Already processing, skipping duplicate execution`);
|
||||
console.warn(`[AuthCallback:${executionId}] This is expected in React Strict Mode (development)`);
|
||||
return;
|
||||
}
|
||||
processingRef.current = true;
|
||||
|
||||
try {
|
||||
console.log('[AuthCallback] Handling OAuth callback...');
|
||||
console.log(`[AuthCallback:${executionId}] Step 1: Extracting token from URL fragment`);
|
||||
|
||||
// Extract JWT from URL fragment (#access_token=...)
|
||||
const hash = window.location.hash.substring(1); // Remove '#'
|
||||
@@ -25,7 +60,7 @@ export default function AuthCallback() {
|
||||
const token = params.get('access_token');
|
||||
|
||||
if (!token) {
|
||||
console.error('[AuthCallback] No access_token in URL fragment');
|
||||
console.error(`[AuthCallback:${executionId}] ❌ No access_token in URL fragment`);
|
||||
navigate('/login', {
|
||||
replace: true,
|
||||
state: { error: 'OAuth login failed - no token received.' }
|
||||
@@ -33,19 +68,25 @@ export default function AuthCallback() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] ✓ Token extracted (length: ${token.length})`);
|
||||
console.log(`[AuthCallback:${executionId}] Step 2: Storing JWT in localStorage`);
|
||||
|
||||
// Store JWT in localStorage
|
||||
localStorage.setItem('stirling_jwt', token);
|
||||
console.log('[AuthCallback] JWT stored in localStorage');
|
||||
console.log(`[AuthCallback:${executionId}] ✓ JWT stored in localStorage`);
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] Step 3: Dispatching 'jwt-available' event`);
|
||||
// Dispatch custom event for other components to react to JWT availability
|
||||
window.dispatchEvent(new CustomEvent('jwt-available'));
|
||||
console.log(`[AuthCallback:${executionId}] ✓ Event dispatched`);
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] Step 4: Validating token with backend`);
|
||||
// Validate the token and load user info
|
||||
// This calls /api/v1/auth/me with the JWT to get user details
|
||||
const { data, error } = await springAuth.getSession();
|
||||
|
||||
if (error || !data.session) {
|
||||
console.error('[AuthCallback] Failed to validate token:', error);
|
||||
console.error(`[AuthCallback:${executionId}] ❌ Failed to validate token:`, error);
|
||||
localStorage.removeItem('stirling_jwt');
|
||||
navigate('/login', {
|
||||
replace: true,
|
||||
@@ -54,14 +95,30 @@ export default function AuthCallback() {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] ✓ Token validated, user: ${data.session.user.username}`);
|
||||
console.log(`[AuthCallback:${executionId}] Step 5: Running platform-specific callback handlers`);
|
||||
|
||||
await handleAuthCallbackSuccess(token);
|
||||
|
||||
console.log('[AuthCallback] Token validated, redirecting to home');
|
||||
console.log(`[AuthCallback:${executionId}] ✓ Callback handlers complete`);
|
||||
console.log(`[AuthCallback:${executionId}] Step 6: Navigating to home page`);
|
||||
|
||||
// Clear the hash from URL and redirect to home page
|
||||
navigate('/', { replace: true });
|
||||
|
||||
const duration = performance.now() - startTime;
|
||||
console.log(`[AuthCallback:${executionId}] ✓ Authentication complete (${duration.toFixed(2)}ms)`);
|
||||
console.log(`[AuthCallback:${executionId}] ════════════════════════════════════`);
|
||||
} catch (error) {
|
||||
console.error('[AuthCallback] Error:', error);
|
||||
const duration = performance.now() - startTime;
|
||||
console.error(`[AuthCallback:${executionId}] ════════════════════════════════════`);
|
||||
console.error(`[AuthCallback:${executionId}] ❌ FATAL ERROR during authentication`);
|
||||
console.error(`[AuthCallback:${executionId}] Error:`, error);
|
||||
console.error(`[AuthCallback:${executionId}] Error name:`, (error as Error)?.name);
|
||||
console.error(`[AuthCallback:${executionId}] Error message:`, (error as Error)?.message);
|
||||
console.error(`[AuthCallback:${executionId}] Error stack:`, (error as Error)?.stack);
|
||||
console.error(`[AuthCallback:${executionId}] Duration before failure: ${duration.toFixed(2)}ms`);
|
||||
console.error(`[AuthCallback:${executionId}] ════════════════════════════════════`);
|
||||
navigate('/login', {
|
||||
replace: true,
|
||||
state: { error: 'OAuth login failed. Please try again.' }
|
||||
@@ -70,7 +127,7 @@ export default function AuthCallback() {
|
||||
};
|
||||
|
||||
handleCallback();
|
||||
}, [navigate]);
|
||||
}, []); // Empty deps - only run once on mount. navigate is stable, processingRef prevents double execution
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
|
||||
@@ -25,6 +25,15 @@ export default function Landing() {
|
||||
|
||||
const loading = authLoading || configLoading || backendProbe.loading;
|
||||
|
||||
// Debug: Track Landing component lifecycle
|
||||
useEffect(() => {
|
||||
const mountId = Math.random().toString(36).substring(7);
|
||||
console.log(`[Landing:${mountId}] 🔵 Component mounted at ${location.pathname}`);
|
||||
return () => {
|
||||
console.log(`[Landing:${mountId}] 🔴 Component unmounting`);
|
||||
};
|
||||
}, [location.pathname]);
|
||||
|
||||
// Periodically probe while backend isn't up so the screen can auto-advance when it comes online
|
||||
useEffect(() => {
|
||||
if (backendProbe.status === 'up' || backendProbe.loginDisabled) {
|
||||
@@ -51,12 +60,20 @@ export default function Landing() {
|
||||
}
|
||||
}, [backendProbe.status, refetch]);
|
||||
|
||||
console.log('[Landing] State:', {
|
||||
console.log('[Landing] ════════════════════════════════════');
|
||||
console.log('[Landing] Render state:', {
|
||||
pathname: location.pathname,
|
||||
loading,
|
||||
authLoading,
|
||||
configLoading,
|
||||
backendLoading: backendProbe.loading,
|
||||
hasSession: !!session,
|
||||
hasConfig: !!config,
|
||||
loginEnabled: config?.enableLogin === true && !backendProbe.loginDisabled,
|
||||
backendStatus: backendProbe.status,
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
console.log('[Landing] ════════════════════════════════════');
|
||||
|
||||
// Show loading while checking auth and config
|
||||
if (loading) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Navigate, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Navigate, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { Text, Stack, Alert } from '@mantine/core';
|
||||
import { springAuth } from '@app/auth/springAuthClient';
|
||||
import { useAuth } from '@app/auth/UseSession';
|
||||
@@ -23,6 +23,7 @@ import LoggedInState from '@app/routes/login/LoggedInState';
|
||||
|
||||
export default function Login() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { session, loading } = useAuth();
|
||||
const { refetch } = useAppConfig();
|
||||
@@ -39,10 +40,84 @@ export default function Login() {
|
||||
const [hasSSOProviders, setHasSSOProviders] = useState(false);
|
||||
const [_enableLogin, setEnableLogin] = useState<boolean | null>(null);
|
||||
const [loginMethod, setLoginMethod] = useState<string>('all');
|
||||
const [ssoAutoLogin, setSsoAutoLogin] = useState(false);
|
||||
const backendProbe = useBackendProbe();
|
||||
const [isFirstTimeSetup, setIsFirstTimeSetup] = useState(false);
|
||||
const [showDefaultCredentials, setShowDefaultCredentials] = useState(false);
|
||||
const loginDisabled = backendProbe.loginDisabled === true || _enableLogin === false;
|
||||
const autoLoginAttempted = useRef(false);
|
||||
const autoLoginErrorRecorded = useRef(false);
|
||||
const isUserPassAllowed = loginMethod === 'all' || loginMethod === 'normal';
|
||||
const isSsoOnlyMode = loginMethod !== 'all' && loginMethod !== 'normal';
|
||||
const isSingleSsoOnly = !isUserPassAllowed && enabledProviders.length === 1;
|
||||
|
||||
const AUTO_LOGIN_ATTEMPTS_KEY = 'stirling_sso_auto_login_attempts';
|
||||
const AUTO_LOGIN_ERRORS_KEY = 'stirling_sso_auto_login_errors';
|
||||
const AUTO_LOGIN_LOGOUT_KEY = 'stirling_sso_auto_login_logged_out';
|
||||
const MAX_AUTO_LOGIN_ATTEMPTS = 2;
|
||||
const MAX_AUTO_LOGIN_ERRORS = 1;
|
||||
|
||||
const readSessionNumber = (key: string) => {
|
||||
if (typeof window === 'undefined') {
|
||||
return 0;
|
||||
}
|
||||
const raw = window.sessionStorage.getItem(key);
|
||||
const value = Number(raw);
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
};
|
||||
|
||||
const writeSessionNumber = (key: string, value: number) => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
window.sessionStorage.setItem(key, String(value));
|
||||
};
|
||||
|
||||
const hasLogoutBlock = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return false;
|
||||
}
|
||||
return window.sessionStorage.getItem(AUTO_LOGIN_LOGOUT_KEY) === '1';
|
||||
};
|
||||
|
||||
const clearLogoutBlock = () => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
window.sessionStorage.removeItem(AUTO_LOGIN_LOGOUT_KEY);
|
||||
};
|
||||
|
||||
const recordAutoLoginAttempt = () => {
|
||||
const attempts = readSessionNumber(AUTO_LOGIN_ATTEMPTS_KEY);
|
||||
writeSessionNumber(AUTO_LOGIN_ATTEMPTS_KEY, attempts + 1);
|
||||
};
|
||||
|
||||
const recordAutoLoginError = () => {
|
||||
const errors = readSessionNumber(AUTO_LOGIN_ERRORS_KEY);
|
||||
writeSessionNumber(AUTO_LOGIN_ERRORS_KEY, errors + 1);
|
||||
};
|
||||
|
||||
const errorFromState = (location.state as { error?: string } | null)?.error;
|
||||
const errorFromQuery = useMemo(() => {
|
||||
if (!searchParams) {
|
||||
return null;
|
||||
}
|
||||
const errorParamKeys = ['error', 'error_description', 'error_code', 'sso_error', 'oauth_error', 'saml_error', 'login_error'];
|
||||
for (const key of errorParamKeys) {
|
||||
const value = searchParams.get(key);
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
for (const [key, value] of searchParams.entries()) {
|
||||
if (key.toLowerCase().includes('error')) {
|
||||
return value || 'Single sign-on failed. Please try again.';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}, [searchParams]);
|
||||
|
||||
const hasSsoLoginError = Boolean(errorFromState || errorFromQuery);
|
||||
|
||||
// Periodically probe while backend isn't up so the screen can auto-advance when it comes online
|
||||
useEffect(() => {
|
||||
@@ -102,6 +177,7 @@ export default function Login() {
|
||||
}
|
||||
|
||||
setEnableLogin(data.enableLogin ?? true);
|
||||
setSsoAutoLogin(Boolean(data.ssoAutoLogin));
|
||||
|
||||
// Set first-time setup flags
|
||||
setIsFirstTimeSetup(data.firstTimeSetup ?? false);
|
||||
@@ -149,6 +225,76 @@ export default function Login() {
|
||||
}
|
||||
}, [enabledProviders, loginMethod]);
|
||||
|
||||
const signInWithProvider = async (provider: OAuthProvider) => {
|
||||
try {
|
||||
setIsSigningIn(true);
|
||||
setError(null);
|
||||
clearLogoutBlock();
|
||||
|
||||
console.log(`[Login] Signing in with provider: ${provider}`);
|
||||
|
||||
// Redirect to Spring OAuth2 endpoint using the actual provider ID from backend
|
||||
// The backend returns the correct registration ID (e.g., 'authentik', 'oidc', 'keycloak')
|
||||
const { error } = await springAuth.signInWithOAuth({
|
||||
provider: provider,
|
||||
options: { redirectTo: `${BASE_PATH}/auth/callback` }
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error(`[Login] ${provider} error:`, error);
|
||||
setError(t('login.failedToSignIn', { provider, message: error.message }) || `Failed to sign in with ${provider}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Login] Unexpected error:`, err);
|
||||
setError(t('login.unexpectedError', { message: err instanceof Error ? err.message : 'Unknown error' }) || 'An unexpected error occurred');
|
||||
} finally {
|
||||
setIsSigningIn(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-login to SSO when enabled and only one SSO option exists
|
||||
useEffect(() => {
|
||||
if (autoLoginAttempted.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const attempts = readSessionNumber(AUTO_LOGIN_ATTEMPTS_KEY);
|
||||
const errors = readSessionNumber(AUTO_LOGIN_ERRORS_KEY);
|
||||
const blockedByErrors = errors >= MAX_AUTO_LOGIN_ERRORS;
|
||||
const blockedByAttempts = attempts >= MAX_AUTO_LOGIN_ATTEMPTS;
|
||||
const blockedByLogout = hasLogoutBlock();
|
||||
|
||||
if (!ssoAutoLogin || loginDisabled || loading || session || backendProbe.status !== 'up') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasSsoLoginError || blockedByErrors || blockedByAttempts || blockedByLogout) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isUserPassAllowed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (enabledProviders.length !== 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
autoLoginAttempted.current = true;
|
||||
recordAutoLoginAttempt();
|
||||
void signInWithProvider(enabledProviders[0]);
|
||||
}, [
|
||||
ssoAutoLogin,
|
||||
loginDisabled,
|
||||
loading,
|
||||
session,
|
||||
backendProbe.status,
|
||||
loginMethod,
|
||||
enabledProviders,
|
||||
signInWithProvider,
|
||||
hasSsoLoginError,
|
||||
]);
|
||||
|
||||
// Handle query params (email prefill, success messages, and session expiry)
|
||||
useEffect(() => {
|
||||
try {
|
||||
@@ -177,10 +323,21 @@ export default function Login() {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (errorFromState) {
|
||||
setError(errorFromState);
|
||||
} else if (errorFromQuery) {
|
||||
setError(errorFromQuery);
|
||||
}
|
||||
|
||||
if (hasSsoLoginError && !autoLoginErrorRecorded.current) {
|
||||
recordAutoLoginError();
|
||||
autoLoginErrorRecorded.current = true;
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore
|
||||
}
|
||||
}, [searchParams, t]);
|
||||
}, [searchParams, t, errorFromState, errorFromQuery, hasSsoLoginError]);
|
||||
|
||||
const baseUrl = window.location.origin + BASE_PATH;
|
||||
|
||||
@@ -243,32 +400,6 @@ export default function Login() {
|
||||
);
|
||||
}
|
||||
|
||||
const signInWithProvider = async (provider: OAuthProvider) => {
|
||||
try {
|
||||
setIsSigningIn(true);
|
||||
setError(null);
|
||||
|
||||
console.log(`[Login] Signing in with provider: ${provider}`);
|
||||
|
||||
// Redirect to Spring OAuth2 endpoint using the actual provider ID from backend
|
||||
// The backend returns the correct registration ID (e.g., 'authentik', 'oidc', 'keycloak')
|
||||
const { error } = await springAuth.signInWithOAuth({
|
||||
provider: provider,
|
||||
options: { redirectTo: `${BASE_PATH}/auth/callback` }
|
||||
});
|
||||
|
||||
if (error) {
|
||||
console.error(`[Login] ${provider} error:`, error);
|
||||
setError(t('login.failedToSignIn', { provider, message: error.message }) || `Failed to sign in with ${provider}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[Login] Unexpected error:`, err);
|
||||
setError(t('login.unexpectedError', { message: err instanceof Error ? err.message : 'Unknown error' }) || 'An unexpected error occurred');
|
||||
} finally {
|
||||
setIsSigningIn(false);
|
||||
}
|
||||
};
|
||||
|
||||
const signInWithEmail = async () => {
|
||||
if (!email || !password) {
|
||||
setError(t('login.pleaseEnterBoth') || 'Please enter both email and password');
|
||||
@@ -283,6 +414,7 @@ export default function Login() {
|
||||
try {
|
||||
setIsSigningIn(true);
|
||||
setError(null);
|
||||
clearLogoutBlock();
|
||||
|
||||
console.log('[Login] Signing in with email:', email);
|
||||
|
||||
@@ -300,6 +432,7 @@ export default function Login() {
|
||||
}
|
||||
} else if (user && session) {
|
||||
console.log('[Login] Email sign in successful');
|
||||
clearLogoutBlock();
|
||||
setRequiresMfa(false);
|
||||
setMfaCode('');
|
||||
// Auth state will update automatically and Landing will redirect to home
|
||||
@@ -320,7 +453,10 @@ export default function Login() {
|
||||
|
||||
return (
|
||||
<AuthLayout>
|
||||
<LoginHeader title={t('login.login') || 'Sign in'} />
|
||||
<LoginHeader
|
||||
title={isSingleSsoOnly ? '' : (t('login.login') || 'Sign in')}
|
||||
centerOnly={isSingleSsoOnly}
|
||||
/>
|
||||
|
||||
{/* Success message */}
|
||||
{successMessage && (
|
||||
@@ -346,15 +482,18 @@ export default function Login() {
|
||||
isSubmitting={isSigningIn}
|
||||
layout="vertical"
|
||||
enabledProviders={enabledProviders}
|
||||
ctaPrefix={isSsoOnlyMode ? t('login.signInWith', 'Sign in with') : undefined}
|
||||
styleVariant="light"
|
||||
useNewStyle={isSsoOnlyMode}
|
||||
/>
|
||||
|
||||
{/* Divider between OAuth and Email - only show if SSO is available and username/password is allowed */}
|
||||
{hasSSOProviders && (loginMethod === 'all' || loginMethod === 'normal') && (
|
||||
{hasSSOProviders && isUserPassAllowed && (
|
||||
<DividerWithText text={t('signup.or', 'or')} respondsToDarkMode={false} opacity={0.4} />
|
||||
)}
|
||||
|
||||
{/* Sign in with email button - only show if SSO providers exist and username/password is allowed */}
|
||||
{hasSSOProviders && !showEmailForm && (loginMethod === 'all' || loginMethod === 'normal') && (
|
||||
{hasSSOProviders && !showEmailForm && isUserPassAllowed && (
|
||||
<div className="auth-section">
|
||||
<button
|
||||
type="button"
|
||||
@@ -368,7 +507,7 @@ export default function Login() {
|
||||
)}
|
||||
|
||||
{/* Email form - show by default if no SSO, or when button clicked, but ONLY if username/password is allowed */}
|
||||
{showEmailForm && (loginMethod === 'all' || loginMethod === 'normal') && (
|
||||
{showEmailForm && isUserPassAllowed && (
|
||||
<div style={{ marginTop: hasSSOProviders ? '1rem' : '0' }}>
|
||||
<EmailPasswordForm
|
||||
email={email}
|
||||
@@ -387,7 +526,7 @@ export default function Login() {
|
||||
)}
|
||||
|
||||
{/* Help section - only show on first-time setup with default credentials and username/password auth allowed */}
|
||||
{isFirstTimeSetup && showDefaultCredentials && (loginMethod === 'all' || loginMethod === 'normal') && (
|
||||
{isFirstTimeSetup && showDefaultCredentials && isUserPassAllowed && (
|
||||
<Alert
|
||||
color="blue"
|
||||
variant="light"
|
||||
|
||||
@@ -142,7 +142,12 @@
|
||||
.oauth-container-vertical {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem; /* 12px */
|
||||
gap: 0.875rem; /* 14px */
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.oauth-container-vertical.oauth-container-single {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.oauth-button-icon {
|
||||
@@ -183,33 +188,114 @@
|
||||
|
||||
.oauth-button-vertical {
|
||||
width: 100%;
|
||||
min-height: 3.5rem; /* 56px */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0.875rem 1.5rem; /* 14px 24px */
|
||||
border: none;
|
||||
border-radius: 999px;
|
||||
background: #0f172a;
|
||||
font-size: 1rem; /* 16px */
|
||||
font-weight: 600;
|
||||
color: #f8fafc;
|
||||
cursor: pointer;
|
||||
gap: 1rem; /* 16px */
|
||||
font-family: inherit;
|
||||
box-shadow: 0 0.4rem 1rem rgba(15, 23, 42, 0.25);
|
||||
transition: background-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.oauth-button-vertical:hover:not(:disabled) {
|
||||
background: #111827;
|
||||
box-shadow: 0 0.55rem 1.25rem rgba(15, 23, 42, 0.3);
|
||||
transform: translateY(-1px);
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-tinted {
|
||||
background: linear-gradient(90deg, color-mix(in srgb, var(--oauth-accent) 65%, #0f172a) 0 6px, #0f172a 6px 100%);
|
||||
}
|
||||
|
||||
.oauth-button-vertical-tinted:hover:not(:disabled) {
|
||||
background: linear-gradient(90deg, color-mix(in srgb, var(--oauth-accent) 75%, #111827) 0 6px, #111827 6px 100%);
|
||||
}
|
||||
|
||||
.oauth-button-vertical-legacy {
|
||||
min-height: 0;
|
||||
justify-content: flex-start;
|
||||
padding: 0.75rem 1rem; /* 12px 16px */
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 0.75rem; /* 12px */
|
||||
background-color: var(--auth-card-bg-light-only);
|
||||
font-size: 1rem; /* 16px */
|
||||
font-weight: 500;
|
||||
color: var(--auth-text-primary-light-only);
|
||||
cursor: pointer;
|
||||
gap: 0.75rem; /* 12px */
|
||||
font-family: inherit;
|
||||
transition: background-color 0.2s ease;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.oauth-button-vertical:hover:not(:disabled) {
|
||||
.oauth-button-vertical-legacy:hover:not(:disabled) {
|
||||
background-color: #f3f4f6;
|
||||
color: var(--auth-text-primary-light-only);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-legacy .mantine-Button-inner,
|
||||
.oauth-button-vertical-legacy .mantine-Button-label {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-legacy .oauth-button-left {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-legacy .oauth-icon-wrapper {
|
||||
width: 1.25rem; /* 20px */
|
||||
height: 1.25rem; /* 20px */
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-legacy .oauth-button-text {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-outline {
|
||||
background: transparent;
|
||||
border: 2px solid #0f172a;
|
||||
color: #0f172a;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.oauth-button-vertical-outline:hover:not(:disabled) {
|
||||
background: #0f172a;
|
||||
color: #f8fafc;
|
||||
box-shadow: 0 0.35rem 0.9rem rgba(15, 23, 42, 0.2);
|
||||
}
|
||||
|
||||
.oauth-button-vertical-light {
|
||||
background: #f8fafc;
|
||||
color: #0f172a;
|
||||
border: 1px solid rgba(15, 23, 42, 0.12);
|
||||
box-shadow: 0 0.25rem 0.75rem rgba(15, 23, 42, 0.12);
|
||||
}
|
||||
|
||||
.oauth-button-vertical-light:hover:not(:disabled) {
|
||||
background: #eef2f7;
|
||||
color: #0f172a;
|
||||
box-shadow: 0 0.35rem 0.9rem rgba(15, 23, 42, 0.16);
|
||||
}
|
||||
|
||||
.oauth-button-vertical:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.oauth-button-vertical:focus-visible {
|
||||
outline: 2px solid var(--auth-border-focus-light-only);
|
||||
outline: 3px solid rgba(59, 130, 246, 0.6);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
@@ -218,15 +304,15 @@
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.oauth-button-vertical .mantine-Button-label {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 0.75rem;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
@@ -249,12 +335,113 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.oauth-container-vertical.oauth-container-single .oauth-button-vertical {
|
||||
max-width: 26.25rem; /* 420px */
|
||||
}
|
||||
|
||||
.oauth-button-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.875rem;
|
||||
min-width: 0;
|
||||
flex: 1 1 auto;
|
||||
}
|
||||
|
||||
.oauth-button-text {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: inherit;
|
||||
line-height: 1.2;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding-bottom: 0.0625rem; /* 1px - prevent descender clipping */
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.oauth-icon-wrapper {
|
||||
width: 2.25rem; /* 36px */
|
||||
height: 2.25rem; /* 36px */
|
||||
border-radius: 0.75rem; /* 12px */
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.oauth-button-vertical-tinted .oauth-icon-wrapper {
|
||||
background: color-mix(in srgb, var(--oauth-accent) 20%, rgba(255, 255, 255, 0.08));
|
||||
border-color: color-mix(in srgb, var(--oauth-accent) 35%, rgba(255, 255, 255, 0.2));
|
||||
}
|
||||
|
||||
.oauth-button-vertical-outline .oauth-icon-wrapper,
|
||||
.oauth-button-vertical-light .oauth-icon-wrapper {
|
||||
background: rgba(15, 23, 42, 0.06);
|
||||
border-color: rgba(15, 23, 42, 0.14);
|
||||
}
|
||||
.oauth-button-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0.85;
|
||||
flex-shrink: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.oauth-arrow-icon {
|
||||
width: 1.1rem; /* 18px */
|
||||
height: 1.1rem; /* 18px */
|
||||
display: block;
|
||||
}
|
||||
|
||||
.sso-demo-block {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.sso-demo-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.sso-demo-card {
|
||||
border: 1px solid rgba(15, 23, 42, 0.08);
|
||||
border-radius: 1rem;
|
||||
padding: 1rem;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 0.25rem 0.75rem rgba(15, 23, 42, 0.06);
|
||||
}
|
||||
|
||||
.sso-demo-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 700;
|
||||
color: var(--auth-text-primary-light-only);
|
||||
margin-bottom: 0.75rem;
|
||||
letter-spacing: 0.01em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* Login Header Styles */
|
||||
.login-header {
|
||||
margin-bottom: 1rem; /* 16px */
|
||||
margin-top: 0.5rem; /* 8px */
|
||||
}
|
||||
|
||||
.login-header-centered {
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem; /* 24px */
|
||||
}
|
||||
|
||||
.login-header-centered .login-header-logos {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.login-header-centered .login-logo-text {
|
||||
height: 2.5rem; /* 40px */
|
||||
}
|
||||
|
||||
.login-header-logos {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -4,17 +4,18 @@ import { useLogoAssets } from '@app/hooks/useLogoAssets';
|
||||
interface LoginHeaderProps {
|
||||
title: string
|
||||
subtitle?: string
|
||||
centerOnly?: boolean
|
||||
}
|
||||
|
||||
export default function LoginHeader({ title, subtitle }: LoginHeaderProps) {
|
||||
export default function LoginHeader({ title, subtitle, centerOnly = false }: LoginHeaderProps) {
|
||||
const { wordmark } = useLogoAssets();
|
||||
|
||||
return (
|
||||
<div className="login-header">
|
||||
<div className={`login-header${centerOnly ? ' login-header-centered' : ''}`}>
|
||||
<div className="login-header-logos">
|
||||
<img src={wordmark.black} alt="Stirling PDF" className="login-logo-text" />
|
||||
</div>
|
||||
<h1 className="login-title">{title}</h1>
|
||||
{title && <h1 className="login-title">{title}</h1>}
|
||||
{subtitle && (
|
||||
<p className="login-subtitle">{subtitle}</p>
|
||||
)}
|
||||
|
||||
@@ -28,9 +28,22 @@ interface OAuthButtonsProps {
|
||||
isSubmitting: boolean
|
||||
layout?: 'vertical' | 'grid' | 'icons'
|
||||
enabledProviders?: OAuthProvider[] // List of full auth paths from backend (e.g., '/oauth2/authorization/google', '/saml2/authenticate/stirling')
|
||||
ctaPrefix?: string
|
||||
styleVariant?: 'neutral' | 'tinted' | 'outline' | 'light'
|
||||
demoMode?: boolean
|
||||
useNewStyle?: boolean
|
||||
}
|
||||
|
||||
export default function OAuthButtons({ onProviderClick, isSubmitting, layout = 'vertical', enabledProviders = [] }: OAuthButtonsProps) {
|
||||
export default function OAuthButtons({
|
||||
onProviderClick,
|
||||
isSubmitting,
|
||||
layout = 'vertical',
|
||||
enabledProviders = [],
|
||||
ctaPrefix,
|
||||
styleVariant = 'neutral',
|
||||
demoMode = false,
|
||||
useNewStyle = false,
|
||||
}: OAuthButtonsProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Debug mode: show all providers for UI testing
|
||||
@@ -65,6 +78,21 @@ export default function OAuthButtons({ onProviderClick, isSubmitting, layout = '
|
||||
return null;
|
||||
}
|
||||
|
||||
const isSingleProvider = providers.length === 1;
|
||||
const isTinted = styleVariant === 'tinted';
|
||||
const isOutline = styleVariant === 'outline';
|
||||
const isLight = styleVariant === 'light';
|
||||
const accentMap: Record<string, string> = {
|
||||
google: '#4285F4',
|
||||
github: '#111827',
|
||||
apple: '#111827',
|
||||
azure: '#0078D4',
|
||||
keycloak: '#2C2C2C',
|
||||
cloudron: '#3B82F6',
|
||||
authentik: '#FA7B17',
|
||||
oidc: '#334155',
|
||||
};
|
||||
|
||||
if (layout === 'icons') {
|
||||
return (
|
||||
<div className="oauth-container-icons">
|
||||
@@ -106,18 +134,30 @@ export default function OAuthButtons({ onProviderClick, isSubmitting, layout = '
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="oauth-container-vertical">
|
||||
<div className={`oauth-container-vertical${useNewStyle && isSingleProvider ? ' oauth-container-single' : ''}`}>
|
||||
{providers.map((p) => (
|
||||
<div key={p.id} title={`${t('login.signInWith', 'Sign in with')} ${p.label}`}>
|
||||
<Button
|
||||
onClick={() => onProviderClick(p.id)}
|
||||
disabled={isSubmitting}
|
||||
className="oauth-button-vertical"
|
||||
disabled={!demoMode && isSubmitting}
|
||||
className={`oauth-button-vertical${useNewStyle && isSingleProvider ? ' oauth-button-vertical-single' : ''}${!useNewStyle ? ' oauth-button-vertical-legacy' : ''}${isTinted ? ' oauth-button-vertical-tinted' : ''}${isOutline ? ' oauth-button-vertical-outline' : ''}${isLight ? ' oauth-button-vertical-light' : ''}`}
|
||||
aria-label={`${t('login.signInWith', 'Sign in with')} ${p.label}`}
|
||||
variant="default"
|
||||
style={isTinted ? { '--oauth-accent': accentMap[p.providerId] || '#334155' } as React.CSSProperties : undefined}
|
||||
>
|
||||
<img src={`${BASE_PATH}/Login/${p.file}`} alt={p.label} className="oauth-icon-tiny" />
|
||||
<span>{p.label}</span>
|
||||
<span className="oauth-button-left">
|
||||
<span className="oauth-icon-wrapper">
|
||||
<img src={`${BASE_PATH}/Login/${p.file}`} alt={p.label} className="oauth-icon-tiny" />
|
||||
</span>
|
||||
<span className="oauth-button-text">{ctaPrefix ? `${ctaPrefix} ${p.label}` : p.label}</span>
|
||||
</span>
|
||||
{useNewStyle && isSingleProvider && (
|
||||
<span className="oauth-button-right" aria-hidden="true">
|
||||
<svg className="oauth-arrow-icon" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M5 12h12m0 0-5-5m5 5-5 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
Reference in New Issue
Block a user