mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-15 19:10:47 +02:00
Bug fixing and debugs (#5704)
Co-authored-by: ConnorYoh <[email protected]>
This commit is contained in:
co-authored by
ConnorYoh
parent
5df466266a
commit
f9d2f36ab7
@@ -54,6 +54,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
console.debug('[Auth] refreshSession: start', { path: window.location.pathname });
|
||||
console.debug('[Auth] Refreshing session...');
|
||||
|
||||
const { data, error } = await springAuth.refreshSession();
|
||||
@@ -70,6 +71,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
console.error('[Auth] Unexpected error during session refresh:', err);
|
||||
setError(err as AuthError);
|
||||
} finally {
|
||||
console.debug('[Auth] refreshSession: done', { hasSession: !!session });
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
@@ -109,6 +111,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const initializeAuth = async () => {
|
||||
try {
|
||||
console.debug(`[Auth:${mountId}] Initializing auth...`);
|
||||
console.debug(`[Auth:${mountId}] Path: ${window.location.pathname} Search: ${window.location.search}`);
|
||||
// Clear any platform-specific cached auth on login page init.
|
||||
if (typeof window !== 'undefined' && window.location.pathname.startsWith('/login')) {
|
||||
await clearPlatformAuthOnLoginInit();
|
||||
@@ -137,6 +140,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setError(err as AuthError);
|
||||
}
|
||||
} finally {
|
||||
console.debug(`[Auth:${mountId}] Initialize auth complete. mounted=${mounted}`);
|
||||
if (mounted) {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { createContext, useContext, useState, useCallback, useEffect, useMemo, useRef, ReactNode } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import licenseService, { LicenseInfo } from '@app/services/licenseService';
|
||||
import { useAppConfig } from '@app/contexts/AppConfigContext';
|
||||
import { getSimulatedLicenseInfo } from '@app/testing/serverExperienceSimulations';
|
||||
@@ -18,6 +19,7 @@ interface LicenseProviderProps {
|
||||
|
||||
export const LicenseProvider: React.FC<LicenseProviderProps> = ({ children }) => {
|
||||
const { config } = useAppConfig();
|
||||
const location = useLocation();
|
||||
const configRef = useRef(config);
|
||||
const [licenseInfo, setLicenseInfo] = useState<LicenseInfo | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
@@ -33,8 +35,8 @@ export const LicenseProvider: React.FC<LicenseProviderProps> = ({ children }) =>
|
||||
let currentConfig = configRef.current;
|
||||
if (!currentConfig) {
|
||||
console.log('[LicenseContext] Config not loaded yet, waiting...');
|
||||
// Wait up to 5 seconds for config to load
|
||||
const maxWait = 5000;
|
||||
// OPTIMIZATION: Reduced from 5s to 1s - config should load quickly
|
||||
const maxWait = 1000;
|
||||
const startTime = Date.now();
|
||||
while (!configRef.current && Date.now() - startTime < maxWait) {
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
@@ -82,10 +84,25 @@ export const LicenseProvider: React.FC<LicenseProviderProps> = ({ children }) =>
|
||||
|
||||
// Fetch license info when config changes (only if user is admin)
|
||||
useEffect(() => {
|
||||
// CRITICAL FIX: Skip license fetch on auth routes to prevent race conditions
|
||||
// during SAML/OAuth callback processing. License isn't needed until user
|
||||
// is authenticated and navigates to main app.
|
||||
const isAuthRoute =
|
||||
location.pathname === '/login' ||
|
||||
location.pathname === '/signup' ||
|
||||
location.pathname === '/auth/callback' ||
|
||||
location.pathname.startsWith('/invite/');
|
||||
|
||||
if (isAuthRoute) {
|
||||
console.log('[LicenseContext] On auth route, skipping license fetch');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (config) {
|
||||
refetchLicense();
|
||||
}
|
||||
}, [config, refetchLicense]);
|
||||
}, [config, refetchLicense, location.pathname]);
|
||||
|
||||
const contextValue: LicenseContextValue = useMemo(
|
||||
() => ({
|
||||
@@ -104,6 +121,10 @@ export const LicenseProvider: React.FC<LicenseProviderProps> = ({ children }) =>
|
||||
);
|
||||
};
|
||||
|
||||
export const useOptionalLicense = (): LicenseContextValue | undefined => {
|
||||
return useContext(LicenseContext);
|
||||
};
|
||||
|
||||
export const useLicense = (): LicenseContextValue => {
|
||||
const context = useContext(LicenseContext);
|
||||
if (!context) {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import React, { createContext, useContext, useState, useCallback, useEffect, ReactNode } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import licenseService, {} from '@app/services/licenseService';
|
||||
import UpdateSeatsModal from '@app/components/shared/UpdateSeatsModal';
|
||||
import { userManagementService } from '@app/services/userManagementService';
|
||||
import { alert } from '@app/components/toast';
|
||||
import { useLicense } from '@app/contexts/LicenseContext';
|
||||
import { useOptionalLicense } from '@app/contexts/LicenseContext';
|
||||
import { resyncExistingLicense } from '@app/utils/licenseCheckoutUtils';
|
||||
|
||||
export interface UpdateSeatsOptions {
|
||||
@@ -27,7 +28,9 @@ interface UpdateSeatsProviderProps {
|
||||
|
||||
export const UpdateSeatsProvider: React.FC<UpdateSeatsProviderProps> = ({ children }) => {
|
||||
const { t } = useTranslation();
|
||||
const { refetchLicense } = useLicense();
|
||||
const location = useLocation();
|
||||
// Use optional hook - won't throw during setup wizard when license provider isn't needed
|
||||
const license = useOptionalLicense();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [currentSeats, setCurrentSeats] = useState<number>(1);
|
||||
@@ -36,6 +39,20 @@ export const UpdateSeatsProvider: React.FC<UpdateSeatsProviderProps> = ({ childr
|
||||
|
||||
// Handle return from Stripe billing portal
|
||||
useEffect(() => {
|
||||
// CRITICAL FIX: Don't run billing check on auth routes to prevent race conditions
|
||||
// during SAML/OAuth callback. This check only matters after successful billing
|
||||
// portal redirects, which never happen on auth routes.
|
||||
const isAuthRoute =
|
||||
location.pathname === '/login' ||
|
||||
location.pathname === '/signup' ||
|
||||
location.pathname === '/auth/callback' ||
|
||||
location.pathname.startsWith('/invite/');
|
||||
|
||||
if (isAuthRoute) {
|
||||
console.log('[UpdateSeatsContext] On auth route, skipping billing return check');
|
||||
return;
|
||||
}
|
||||
|
||||
const handleBillingReturn = async () => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const seatsUpdated = urlParams.get('seats_updated');
|
||||
@@ -58,7 +75,7 @@ export const UpdateSeatsProvider: React.FC<UpdateSeatsProviderProps> = ({ childr
|
||||
console.log('License synced successfully after seat update');
|
||||
|
||||
// Refresh global license context
|
||||
await refetchLicense();
|
||||
await license?.refetchLicense();
|
||||
|
||||
// Get updated license info for notification
|
||||
const updatedLicense = await licenseService.getLicenseInfo();
|
||||
@@ -89,8 +106,12 @@ export const UpdateSeatsProvider: React.FC<UpdateSeatsProviderProps> = ({ childr
|
||||
}
|
||||
};
|
||||
|
||||
handleBillingReturn();
|
||||
}, [t, refetchLicense]);
|
||||
// CRITICAL FIX: Properly handle async function and catch errors
|
||||
handleBillingReturn().catch((error) => {
|
||||
console.error('[UpdateSeatsContext] Error in billing return handler:', error);
|
||||
// Don't throw - this is initialization, should not block rendering
|
||||
});
|
||||
}, [t, location.pathname, license]);
|
||||
|
||||
const openUpdateSeats = useCallback(async (options: UpdateSeatsOptions = {}) => {
|
||||
try {
|
||||
@@ -143,8 +164,8 @@ export const UpdateSeatsProvider: React.FC<UpdateSeatsProviderProps> = ({ childr
|
||||
setCurrentOptions({});
|
||||
|
||||
// Refetch license after modal closes to update UI
|
||||
refetchLicense();
|
||||
}, [refetchLicense]);
|
||||
license?.refetchLicense();
|
||||
}, [license]);
|
||||
|
||||
const handleUpdateSeats = useCallback(
|
||||
async (newSeatCount: number): Promise<string> => {
|
||||
|
||||
@@ -33,6 +33,7 @@ export default function AuthCallback() {
|
||||
console.log(`[AuthCallback:${executionId}] Starting authentication callback`);
|
||||
console.log(`[AuthCallback:${executionId}] URL: ${window.location.href}`);
|
||||
console.log(`[AuthCallback:${executionId}] Hash: ${window.location.hash}`);
|
||||
console.log(`[AuthCallback:${executionId}] Document readyState: ${document.readyState}`);
|
||||
|
||||
if (typeof window !== 'undefined' && window.sessionStorage.getItem('stirling_sso_auto_login_logged_out') === '1') {
|
||||
console.warn(`[AuthCallback:${executionId}] ⚠️ Logout block active, skipping token processing`);
|
||||
@@ -79,6 +80,7 @@ export default function AuthCallback() {
|
||||
// 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}] Elapsed after jwt-available: ${(performance.now() - startTime).toFixed(2)}ms`);
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] Step 4: Validating token with backend`);
|
||||
// Validate the token and load user info
|
||||
@@ -101,7 +103,14 @@ export default function AuthCallback() {
|
||||
await handleAuthCallbackSuccess(token);
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] ✓ Callback handlers complete`);
|
||||
console.log(`[AuthCallback:${executionId}] Step 6: Navigating to home page`);
|
||||
console.log(`[AuthCallback:${executionId}] Step 6: Waiting for context stabilization`);
|
||||
|
||||
// Wait for all context providers to process jwt-available event
|
||||
// This prevents infinite render loop when coming from cross-domain SAML redirect
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
console.log(`[AuthCallback:${executionId}] Elapsed after stabilization wait: ${(performance.now() - startTime).toFixed(2)}ms`);
|
||||
|
||||
console.log(`[AuthCallback:${executionId}] Step 7: Navigating to home page`);
|
||||
|
||||
// Clear the hash from URL and redirect to home page
|
||||
navigate('/', { replace: true });
|
||||
|
||||
@@ -29,10 +29,16 @@ export default function Landing() {
|
||||
useEffect(() => {
|
||||
const mountId = Math.random().toString(36).substring(7);
|
||||
console.log(`[Landing:${mountId}] 🔵 Component mounted at ${location.pathname}`);
|
||||
console.log(`[Landing:${mountId}] Mount state:`, {
|
||||
authLoading,
|
||||
configLoading,
|
||||
backendLoading: backendProbe.loading,
|
||||
hasSession: !!session,
|
||||
});
|
||||
return () => {
|
||||
console.log(`[Landing:${mountId}] 🔴 Component unmounting`);
|
||||
};
|
||||
}, [location.pathname]);
|
||||
}, [location.pathname, authLoading, configLoading, backendProbe.loading, session]);
|
||||
|
||||
// Periodically probe while backend isn't up so the screen can auto-advance when it comes online
|
||||
useEffect(() => {
|
||||
|
||||
@@ -197,6 +197,11 @@ export default function Login() {
|
||||
setLoginMethod(data.loginMethod || 'all');
|
||||
} catch (err) {
|
||||
console.error('[Login] Failed to fetch enabled providers:', err);
|
||||
// Set default values on error to ensure UI remains functional
|
||||
// Login method defaults to 'all' to show both SSO and email/password options
|
||||
setEnableLogin(true);
|
||||
setLoginMethod('all');
|
||||
setEnabledProviders([]);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user