Add debugging logs in stachAuthService

This commit is contained in:
Abhishek Kumar 2025-09-09 19:10:18 +05:30
parent 695b43af28
commit a5524dbbac
15 changed files with 299 additions and 56 deletions

View file

@ -2,11 +2,25 @@
import React from 'react';
import logger from '@/lib/logger';
import { useAuthContext } from '../providers/AuthProvider';
export function useAuth() {
const renderCount = React.useRef(0);
renderCount.current++;
const context = useAuthContext();
logger.debug('[useAuth] Hook called', {
renderCount: renderCount.current,
hasUser: !!context.user,
userId: context.user?.id,
isAuthenticated: context.isAuthenticated,
loading: context.loading,
provider: context.provider
});
// Memoize functions that are recreated on every render
const logout = React.useCallback(() => context.service.logout(), [context.service]);
const redirectToLogin = React.useCallback(() => context.service.redirectToLogin(), [context.service]);

View file

@ -3,10 +3,28 @@
import { StackClientApp,StackProvider, StackTheme, useUser as useStackUser } from '@stackframe/stack';
import React, { useEffect, useState } from 'react';
import logger from '@/lib/logger';
import { StackAuthService } from '../services';
import type { AuthUser } from '../types';
import { AuthContext } from './AuthProvider';
// Create a singleton StackClientApp instance to prevent multiple initializations
let stackClientAppInstance: StackClientApp<true, string> | null = null;
function getStackClientApp(): StackClientApp<true, string> {
if (!stackClientAppInstance) {
logger.debug('[StackProviderWrapper] Creating singleton StackClientApp instance');
stackClientAppInstance = new StackClientApp({
tokenStore: "nextjs-cookie",
urls: {
afterSignIn: "/after-sign-in"
}
});
}
return stackClientAppInstance;
}
interface StackProviderWrapperProps {
service: StackAuthService;
children: React.ReactNode;
@ -14,29 +32,84 @@ interface StackProviderWrapperProps {
// Stack-specific context provider that uses the useUser hook
function StackAuthContextProvider({ service, children }: { service: StackAuthService; children: React.ReactNode }) {
const [loading, setLoading] = useState(true);
const renderCount = React.useRef(0);
const lastUserId = React.useRef<string | undefined>(undefined);
renderCount.current++;
logger.debug(`[StackAuthContextProvider] Render #${renderCount.current} - Starting`);
const stackUser = useStackUser(); // Always call the hook
const [isInitialized, setIsInitialized] = useState(false);
// Track if user actually changed
const userChanged = lastUserId.current !== stackUser?.id;
if (userChanged) {
lastUserId.current = stackUser?.id;
}
logger.debug(`[StackAuthContextProvider] Render #${renderCount.current} - stackUser:`, {
hasUser: !!stackUser,
userId: stackUser?.id,
isInitialized,
userChanged
});
useEffect(() => {
// Set the user instance in the service
if (service instanceof StackAuthService && stackUser) {
service.setUserInstance(stackUser);
setLoading(false);
} else if (!stackUser) {
setLoading(false);
// Only log and update if user actually changed
if (!userChanged && isInitialized) {
return;
}
}, [service, stackUser]);
const getAccessToken = React.useCallback(() => service.getAccessToken(), [service]);
logger.debug('[StackAuthContextProvider] useEffect triggered (user changed)', {
hasUser: !!stackUser,
userId: stackUser?.id,
isInitialized,
isStackAuthService: service instanceof StackAuthService
});
const contextValue = React.useMemo(() => ({
service,
user: stackUser as AuthUser, // Pass the actual Stack CurrentUser
isAuthenticated: service.isAuthenticated(),
loading,
getAccessToken,
provider: service.getProviderName(),
}), [service, stackUser, loading, getAccessToken]);
// Only update the service once when user becomes available
if (!isInitialized && service instanceof StackAuthService && stackUser) {
logger.debug('[StackAuthContextProvider] Setting user instance in service', {
userId: stackUser.id
});
service.setUserInstance(stackUser);
setIsInitialized(true);
}
}, [service, stackUser, isInitialized, userChanged]);
const getAccessToken = React.useCallback(() => {
logger.debug('[StackAuthContextProvider] getAccessToken called');
return service.getAccessToken();
}, [service]);
// Stabilize the context value to prevent unnecessary re-renders
const contextValue = React.useMemo(() => {
const isAuth = service.isAuthenticated();
// IMPORTANT: Stay in loading state until service is initialized (has user set)
// Even if stackUser exists, we're still loading until setUserInstance is called
const loadingState = !isInitialized;
const value = {
service,
user: stackUser as AuthUser, // Pass the actual Stack CurrentUser
isAuthenticated: isAuth,
loading: loadingState, // Loading until service is initialized
getAccessToken,
provider: service.getProviderName(),
};
logger.debug('[StackAuthContextProvider] Context value created', {
isAuthenticated: isAuth,
loading: loadingState,
hasUser: !!value.user,
userId: stackUser?.id,
isInitialized,
provider: value.provider,
serviceHasUser: isAuth
});
return value;
}, [service, stackUser, isInitialized, getAccessToken]);
return (
<AuthContext.Provider value={contextValue}>
@ -46,13 +119,10 @@ function StackAuthContextProvider({ service, children }: { service: StackAuthSer
}
export function StackProviderWrapper({ service, children }: StackProviderWrapperProps) {
// Create the Stack client app here, only when actually needed
const stackClientApp = new StackClientApp({
tokenStore: "nextjs-cookie",
urls: {
afterSignIn: "/after-sign-in"
}
});
logger.debug('[StackProviderWrapper] Rendering wrapper');
// Use the singleton instance
const stackClientApp = getStackClientApp();
return (
<StackProvider app={stackClientApp}>

View file

@ -1,16 +1,30 @@
import logger from '@/lib/logger';
import type { AuthProvider } from '../types';
import type { IAuthService } from './interface';
import { LocalAuthService } from './localAuthService';
import { StackAuthService } from './stackAuthService';
// Singleton instances for auth services
let stackServiceInstance: StackAuthService | null = null;
let localServiceInstance: LocalAuthService | null = null;
export function createAuthService(provider?: AuthProvider | string): IAuthService {
const authProvider = provider || process.env.NEXT_PUBLIC_AUTH_PROVIDER || 'stack';
switch (authProvider) {
case 'stack':
return new StackAuthService();
if (!stackServiceInstance) {
logger.debug('[createAuthService] Creating singleton StackAuthService instance');
stackServiceInstance = new StackAuthService();
}
return stackServiceInstance;
case 'local':
return new LocalAuthService();
if (!localServiceInstance) {
logger.debug('[createAuthService] Creating singleton LocalAuthService instance');
localServiceInstance = new LocalAuthService();
}
return localServiceInstance;
// Future providers can be added here
// case 'auth0':
// return new Auth0Service();
@ -18,7 +32,10 @@ export function createAuthService(provider?: AuthProvider | string): IAuthServic
// return new SupabaseService();
default:
console.warn(`Unknown auth provider: ${authProvider}, falling back to local`);
return new LocalAuthService();
if (!localServiceInstance) {
localServiceInstance = new LocalAuthService();
}
return localServiceInstance;
}
}

View file

@ -8,24 +8,62 @@ import type { IAuthService } from './interface';
export class StackAuthService implements IAuthService {
private userInstance: CurrentUser | null = null;
private callCount = {
setUserInstance: 0,
getAccessToken: 0,
refreshToken: 0,
getCurrentUser: 0,
isAuthenticated: 0
};
// Set the user instance from the Stack useUser hook
setUserInstance(user: CurrentUser) {
this.callCount.setUserInstance++;
logger.debug('[StackAuthService] setUserInstance called', {
callCount: this.callCount.setUserInstance,
userId: user?.id,
hadPreviousUser: !!this.userInstance,
previousUserId: this.userInstance?.id,
timestamp: new Date().toISOString()
});
this.userInstance = user;
logger.debug('[StackAuthService] setUserInstance completed - user is now set');
}
async getAccessToken(): Promise<string> {
this.callCount.getAccessToken++;
logger.debug('[StackAuthService] getAccessToken called', {
callCount: this.callCount.getAccessToken,
hasUser: !!this.userInstance,
userId: this.userInstance?.id
});
if (!this.userInstance) {
logger.error('[StackAuthService] getAccessToken - User not initialized');
throw new Error('User not initialized');
}
logger.debug('[StackAuthService] Calling user.getAuthJson()');
const authJson = await this.userInstance.getAuthJson();
logger.debug('[StackAuthService] getAuthJson returned', {
hasToken: !!authJson.accessToken,
tokenLength: authJson.accessToken?.length
});
if (!authJson.accessToken) {
logger.error('[StackAuthService] No access token available');
throw new Error('No access token available');
}
return authJson.accessToken;
}
async refreshToken(): Promise<string> {
this.callCount.refreshToken++;
logger.debug('[StackAuthService] refreshToken called', {
callCount: this.callCount.refreshToken,
hasUser: !!this.userInstance
});
if (!this.userInstance) {
throw new Error('User not initialized');
}
@ -38,12 +76,27 @@ export class StackAuthService implements IAuthService {
}
async getCurrentUser(): Promise<CurrentUser | null> {
this.callCount.getCurrentUser++;
logger.debug('[StackAuthService] getCurrentUser called', {
callCount: this.callCount.getCurrentUser,
hasUser: !!this.userInstance,
userId: this.userInstance?.id
});
// Return the actual Stack user instance
return this.userInstance;
}
isAuthenticated(): boolean {
return !!this.userInstance;
this.callCount.isAuthenticated++;
const isAuth = !!this.userInstance;
logger.debug('[StackAuthService] isAuthenticated called', {
callCount: this.callCount.isAuthenticated,
result: isAuth,
hasUserInstance: !!this.userInstance,
userId: this.userInstance?.id,
timestamp: new Date().toISOString()
});
return isAuth;
}
redirectToLogin(): void {

View file

@ -27,27 +27,43 @@ export function debounce<T extends (...args: unknown[]) => unknown>(func: T, wai
}
export async function getRedirectUrl(token: string, permissions: { id: string }[] = []) {
console.log('[getRedirectUrl] Called with:', {
hasToken: !!token,
tokenLength: token?.length,
permissionsCount: permissions.length,
permissions: permissions.map(p => p.id)
});
try {
console.log('[getRedirectUrl] Calling getAuthUserApiV1UserAuthUserGet...');
const authUser = await getAuthUserApiV1UserAuthUserGet({
headers: {
Authorization: `Bearer ${token}`,
},
});
console.log('[getRedirectUrl] Auth user response:', {
hasData: !!authUser.data,
isSuperuser: authUser.data?.is_superuser,
userId: authUser.data?.id
});
if (authUser.data?.is_superuser) {
console.log('[getRedirectUrl] User is superuser, redirecting to /superadmin');
return "/superadmin";
}
const hasAdminPermission = permissions.some(p => p.id === 'admin');
console.log('[getRedirectUrl] Admin permission check:', { hasAdminPermission });
// If the user doesn't have admin permissions, redirect them to
// usage page
if (!hasAdminPermission) {
console.log('[getRedirectUrl] No admin permission, redirecting to /usage');
return "/usage";
}
console.log('[getRedirectUrl] Has admin permission, redirecting to /create-workflow');
return "/create-workflow";
} catch (error) {
console.error("Failed to fetch auth user:", error);
console.error("[getRedirectUrl] Failed to fetch auth user:", error);
// Re-throw the error so the caller can handle it
throw error;
}