351 lines
11 KiB
TypeScript
351 lines
11 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
|
import { getAuthToken, saveAuthToken, deleteAuthToken, saveUserId, getUserId } from '../../hooks/useJWT';
|
|
import { getCurrentUserId } from '@/utils/getCurrentUserId';
|
|
import { useRegister } from '@/src/api-hooks/auth.api';
|
|
import { AuthState, AuthContextType, LoginCredentials, RegisterData, User, UserDetails } from '@/src/types/auth';
|
|
import { trpc } from '@/src/trpc-client';
|
|
import { StorageServiceCasual } from 'common-ui';
|
|
import { FORCE_LOGOUT_EVENT } from 'common-ui/src/lib/const-strs';
|
|
import { useQueryClient } from '@tanstack/react-query';
|
|
import { useRouter } from 'expo-router';
|
|
import { DeviceEventEmitter } from 'react-native';
|
|
import constants from '@/src/constants';
|
|
import type { AuthRedirectOptions, ReactParentComponent } from '@packages/shared';
|
|
|
|
/**
|
|
* Only a credential rejection proves the stored token is dead. Offline, a
|
|
* timeout or a 5xx must never sign the user out: the stored credentials are
|
|
* trusted until the backend actually says no.
|
|
*/
|
|
const isCredentialError = (error: unknown): boolean => {
|
|
const trpcError = error as { data?: { code?: string }; shape?: { data?: { code?: string } } } | null;
|
|
const code = trpcError?.data?.code ?? trpcError?.shape?.data?.code;
|
|
return code === 'UNAUTHORIZED' || code === 'FORBIDDEN';
|
|
};
|
|
|
|
export interface RedirectState extends AuthRedirectOptions {
|
|
targetUrl: string;
|
|
queryParams: Record<string, any>;
|
|
timestamp: number;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
export const AuthProvider: React.FC<ReactParentComponent> = ({ children }) => {
|
|
const router = useRouter();
|
|
const queryClient = useQueryClient();
|
|
const [authState, setAuthState] = useState<AuthState>({
|
|
user: null,
|
|
userDetails: null,
|
|
isAuthenticated: false,
|
|
isLoading: true,
|
|
token: null,
|
|
});
|
|
|
|
// const loginMutation = useLogin();
|
|
const loginMutation = trpc.user.auth.login.useMutation();
|
|
const registerMutation = useRegister();
|
|
|
|
// Drop the session everywhere: stored token, cached queries and state.
|
|
const clearSession = useCallback(async (): Promise<void> => {
|
|
try {
|
|
await deleteAuthToken();
|
|
} catch {
|
|
// Still clear local state even if deleting the token fails.
|
|
}
|
|
queryClient.clear();
|
|
setAuthState({
|
|
user: null,
|
|
userDetails: null,
|
|
isAuthenticated: false,
|
|
isLoading: false,
|
|
token: null,
|
|
});
|
|
}, [queryClient]);
|
|
|
|
// Initialize auth state on app startup
|
|
useEffect(() => {
|
|
const initializeAuth = async () => {
|
|
try {
|
|
const token = await getAuthToken();
|
|
const userId = await getCurrentUserId();
|
|
|
|
if (token && userId) {
|
|
// Trust the stored credentials: render the app now and let the
|
|
// background getSelfData read confirm (or reject) them.
|
|
setAuthState({
|
|
user: {
|
|
id: userId,
|
|
name: '', // Will be populated by useQuery
|
|
email: '',
|
|
mobile: '',
|
|
profileImage: '',
|
|
createdAt: '',
|
|
},
|
|
userDetails: null,
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
token,
|
|
});
|
|
} else {
|
|
setAuthState(prev => ({
|
|
...prev,
|
|
userDetails: null,
|
|
isLoading: false,
|
|
}));
|
|
}
|
|
} catch (error) {
|
|
setAuthState(prev => ({
|
|
...prev,
|
|
userDetails: null,
|
|
isLoading: false,
|
|
}));
|
|
}
|
|
};
|
|
|
|
initializeAuth();
|
|
}, []);
|
|
|
|
// Fetch user data using tRPC query
|
|
const { data: selfData, error: selfDataError, refetch: refetchSelfData } = trpc.user.user.getSelfData.useQuery(undefined, {
|
|
enabled: !!(authState.token && authState.user?.id), // Only run if we have token and userId
|
|
retry: false, // Don't retry on auth errors
|
|
refetchOnMount: true, // Refetch on every component mount (app startup)
|
|
refetchOnWindowFocus: false, // Don't refetch on window focus
|
|
staleTime: 0, // Consider data stale immediately
|
|
});
|
|
|
|
// Handle user data response
|
|
useEffect(() => {
|
|
if (selfData && authState.isAuthenticated) {
|
|
const { user } = selfData.data;
|
|
|
|
setAuthState(prev => ({
|
|
...prev,
|
|
user: {
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
mobile: user.mobile,
|
|
profileImage: user.profileImage,
|
|
createdAt: '',
|
|
},
|
|
userDetails: user,
|
|
isLoading: false,
|
|
}));
|
|
} else if (selfDataError && authState.isAuthenticated && isCredentialError(selfDataError)) {
|
|
// The backend rejected the stored token: drop the session.
|
|
void clearSession();
|
|
}
|
|
// Any other failure (offline, timeout, 5xx) keeps the trusted session; the
|
|
// screen that needs the data shows its own error/retry.
|
|
}, [selfData, selfDataError, authState.isAuthenticated, clearSession]);
|
|
|
|
// src/trpc-client.ts emits this whenever the API answers 401 UNAUTHORIZED, so
|
|
// a revoked token is dropped even when the failing call is not getSelfData.
|
|
useEffect(() => {
|
|
const subscription = DeviceEventEmitter.addListener(FORCE_LOGOUT_EVENT, () => {
|
|
void clearSession();
|
|
});
|
|
return () => subscription.remove();
|
|
}, [clearSession]);
|
|
|
|
// Helper function to handle redirect after successful login
|
|
const handlePostLoginRedirect = async () => {
|
|
try {
|
|
const storedData = await StorageServiceCasual.getItem(constants.AUTH_REDIRECT_KEY);
|
|
|
|
if (storedData) {
|
|
const redirectState: RedirectState = JSON.parse(storedData);
|
|
|
|
// Clear the stored state
|
|
await StorageServiceCasual.removeItem(constants.AUTH_REDIRECT_KEY);
|
|
|
|
// Check if the redirect state is not too old (24 hours)
|
|
const isExpired = Date.now() - redirectState.timestamp > 24 * 60 * 60 * 1000;
|
|
if (isExpired) {
|
|
router.replace('/');
|
|
return;
|
|
}
|
|
|
|
// Build the path with query params
|
|
let targetPath = redirectState.targetUrl;
|
|
const queryParams = redirectState.queryParams;
|
|
|
|
if (Object.keys(queryParams).length > 0) {
|
|
const searchParams = new URLSearchParams();
|
|
Object.entries(queryParams).forEach(([key, value]) => {
|
|
if (value !== undefined && value !== null) {
|
|
searchParams.set(key, String(value));
|
|
}
|
|
});
|
|
targetPath += `?${searchParams.toString()}`;
|
|
}
|
|
|
|
// Navigate to the page the user was trying to reach.
|
|
router.replace(targetPath as any);
|
|
} else {
|
|
// No stored redirect state, go back to the previous screen.
|
|
router.back();
|
|
}
|
|
} catch (error) {
|
|
// Fallback to home on error
|
|
router.replace('/');
|
|
}
|
|
};
|
|
|
|
const loginWithToken = async (token: string, user: User): Promise<void> => {
|
|
try {
|
|
setAuthState(prev => ({ ...prev, isLoading: true }));
|
|
|
|
await saveAuthToken(token);
|
|
await saveUserId(user.id.toString());
|
|
|
|
setAuthState({
|
|
user: {
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
mobile: user.mobile,
|
|
profileImage: user.profileImage,
|
|
createdAt: '',
|
|
},
|
|
userDetails: user,
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
token,
|
|
});
|
|
|
|
// Handle post-login redirect after auth state is set
|
|
handlePostLoginRedirect();
|
|
} catch (error) {
|
|
setAuthState(prev => ({ ...prev, isLoading: false }));
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
const login = async (credentials: LoginCredentials): Promise<void> => {
|
|
try {
|
|
setAuthState(prev => ({ ...prev, isLoading: true }));
|
|
|
|
const response = await loginMutation.mutateAsync(credentials);
|
|
// const response = loginMutation.mutate(credentials);
|
|
const { token, user } = response.data;
|
|
|
|
await saveAuthToken(token);
|
|
await saveUserId(user.id.toString());
|
|
|
|
setAuthState({
|
|
user: {
|
|
id: user.id,
|
|
name: user.name || null,
|
|
email: user.email,
|
|
mobile: user.mobile,
|
|
profileImage: user.profileImage,
|
|
createdAt: '',
|
|
},
|
|
userDetails: user,
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
token,
|
|
});
|
|
|
|
// Refetch user details to ensure we have the latest data
|
|
refetchSelfData();
|
|
} catch (error) {
|
|
setAuthState(prev => ({ ...prev, isLoading: false }));
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
|
|
const register = async (data: RegisterData): Promise<void> => {
|
|
try {
|
|
setAuthState(prev => ({ ...prev, isLoading: true }));
|
|
|
|
const response = await registerMutation.mutateAsync(data);
|
|
const { token, user } = response;
|
|
|
|
await saveAuthToken(token);
|
|
await saveUserId(user.id.toString());
|
|
|
|
setAuthState({
|
|
user: {
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
mobile: user.mobile,
|
|
profileImage: user.profileImage,
|
|
createdAt: '',
|
|
},
|
|
userDetails: user,
|
|
isAuthenticated: true,
|
|
isLoading: false,
|
|
token,
|
|
});
|
|
|
|
// Refetch user details to ensure we have the latest data
|
|
refetchSelfData();
|
|
} catch (error) {
|
|
setAuthState(prev => ({ ...prev, isLoading: false }));
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
// Manual logout and forced logout (rejected credentials) are the same thing.
|
|
const logout = clearSession;
|
|
|
|
const updateUser = (userData: Partial<User>): void => {
|
|
setAuthState(prev => ({
|
|
...prev,
|
|
user: prev.user ? { ...prev.user, ...userData } : null,
|
|
}));
|
|
};
|
|
|
|
const updateUserDetails = (userDetailsData: Partial<UserDetails>): void => {
|
|
setAuthState(prev => ({
|
|
...prev,
|
|
userDetails: prev.userDetails ? { ...prev.userDetails, ...userDetailsData } : null,
|
|
}));
|
|
};
|
|
|
|
const contextValue: AuthContextType = {
|
|
...authState,
|
|
login,
|
|
loginWithToken,
|
|
register,
|
|
logout,
|
|
updateUser,
|
|
updateUserDetails,
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider value={contextValue}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useAuth = (): AuthContextType => {
|
|
const context = useContext(AuthContext);
|
|
if (context === undefined) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
return context;
|
|
};
|
|
|
|
/**
|
|
* Non-throwing auth read for hooks that can render OUTSIDE the AuthProvider
|
|
* (e.g. UpdateChecker sits above it). Returns null when there is no provider.
|
|
*/
|
|
export const useAuthOptional = (): AuthContextType | null => {
|
|
return useContext(AuthContext) ?? null;
|
|
};
|
|
|
|
export const useUserDetails = (): UserDetails | null => {
|
|
const context = useContext(AuthContext);
|
|
if (context === undefined) {
|
|
throw new Error('useUserDetails must be used within an AuthProvider');
|
|
}
|
|
return context.userDetails;
|
|
};
|