forked from cardosofelipe/fast-next-template
Refactor useAuth hooks for improved type safety, error handling, and compliance with auto-generated API client
- Migrated `useAuth` hooks to use functions from auto-generated API client for improved maintainability and OpenAPI compliance. - Replaced manual API calls with SDK functions (`login`, `register`, `logout`, etc.) and added error type guards for runtime safety (`isTokenWithUser`, `isSuccessResponse`). - Enhanced hooks with better error logging, optional success callbacks, and stricter type annotations. - Refactored `Logout` and `LogoutAll` mutations to handle missing tokens gracefully and clear local state on server failure. - Added tests for API type guards and updated functionality of hooks to validate proper behaviors. - Removed legacy `client-config.ts` to align with new API client utilization. - Improved inline documentation for hooks with detailed descriptions and usage guidance.
This commit is contained in:
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* Configure the generated API client
|
||||
* Integrates @hey-api/openapi-ts client with our auth logic
|
||||
*
|
||||
* This file wraps the auto-generated client without modifying generated code
|
||||
* Note: @hey-api client doesn't support axios-style interceptors
|
||||
* We configure it to work with existing manual client.ts for now
|
||||
*/
|
||||
|
||||
import { client } from './generated/client.gen';
|
||||
import config from '@/config/app.config';
|
||||
|
||||
/**
|
||||
* Configure generated client with base URL
|
||||
* Auth token injection handled via fetch interceptor pattern
|
||||
*/
|
||||
export function configureApiClient() {
|
||||
client.setConfig({
|
||||
baseURL: config.api.url,
|
||||
});
|
||||
}
|
||||
|
||||
// Configure client on module load
|
||||
configureApiClient();
|
||||
|
||||
// Re-export configured client for use in hooks
|
||||
export { client as generatedClient };
|
||||
|
||||
// Re-export all SDK functions
|
||||
export * from './generated/sdk.gen';
|
||||
|
||||
// Re-export types
|
||||
export type * from './generated/types.gen';
|
||||
|
||||
// Also export manual client for backward compatibility
|
||||
export { apiClient } from './client';
|
||||
@@ -1,98 +1,106 @@
|
||||
/**
|
||||
* API Client with secure token refresh and error handling
|
||||
* Implements singleton refresh pattern to prevent race conditions
|
||||
* API Client Configuration with Interceptors
|
||||
*
|
||||
* This module configures the auto-generated API client with:
|
||||
* - Token refresh interceptor (prevents race conditions with singleton pattern)
|
||||
* - Request interceptor (adds Authorization header)
|
||||
* - Response interceptor (handles 401, 403, 429, 500 errors)
|
||||
*
|
||||
* IMPORTANT: Do NOT modify generated files. All customization happens here.
|
||||
*
|
||||
* @module lib/api/client
|
||||
*/
|
||||
|
||||
import axios, { AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { parseAPIError, type APIErrorResponse } from './errors';
|
||||
import type { AxiosError, InternalAxiosRequestConfig, AxiosResponse } from 'axios';
|
||||
import { client } from './generated/client.gen';
|
||||
import { refreshToken as refreshTokenFn } from './generated/sdk.gen';
|
||||
import config from '@/config/app.config';
|
||||
|
||||
/**
|
||||
* Separate axios instance for auth endpoints
|
||||
* Prevents interceptor loops during token refresh
|
||||
*/
|
||||
const authClient = axios.create({
|
||||
baseURL: config.api.url,
|
||||
timeout: config.api.timeout,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Main API client instance
|
||||
*/
|
||||
export const apiClient = axios.create({
|
||||
baseURL: config.api.url,
|
||||
timeout: config.api.timeout,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Token refresh state
|
||||
* Singleton pattern prevents multiple simultaneous refresh requests
|
||||
* Token refresh state management (singleton pattern)
|
||||
* Prevents race conditions when multiple requests fail with 401 simultaneously
|
||||
*/
|
||||
let isRefreshing = false;
|
||||
let refreshPromise: Promise<string> | null = null;
|
||||
|
||||
/**
|
||||
* Auth store accessor
|
||||
* Dynamically imported to avoid circular dependencies
|
||||
*/
|
||||
const getAuthStore = async () => {
|
||||
const { useAuthStore } = await import('@/stores/authStore');
|
||||
return useAuthStore.getState();
|
||||
};
|
||||
|
||||
/**
|
||||
* Refresh access token using refresh token
|
||||
* Implements singleton pattern to prevent race conditions
|
||||
* @returns Promise resolving to new access token
|
||||
*
|
||||
* @returns Promise<string> New access token
|
||||
* @throws Error if refresh fails
|
||||
*/
|
||||
async function refreshAccessToken(): Promise<string> {
|
||||
// If already refreshing, return existing promise
|
||||
// Singleton pattern: reuse in-flight refresh request
|
||||
if (isRefreshing && refreshPromise) {
|
||||
return refreshPromise;
|
||||
}
|
||||
|
||||
// Start new refresh
|
||||
isRefreshing = true;
|
||||
|
||||
refreshPromise = (async () => {
|
||||
try {
|
||||
const refreshToken = useAuthStore.getState().refreshToken;
|
||||
const authStore = await getAuthStore();
|
||||
const { refreshToken } = authStore;
|
||||
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available');
|
||||
}
|
||||
|
||||
// Use separate auth client to avoid interceptor loop
|
||||
const response = await authClient.post<{
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
expires_in?: number;
|
||||
token_type: string;
|
||||
}>('/auth/refresh', {
|
||||
refresh_token: refreshToken,
|
||||
});
|
||||
|
||||
// Validate response structure
|
||||
if (!response.data?.access_token || !response.data?.refresh_token) {
|
||||
throw new Error('Invalid refresh response format');
|
||||
if (config.debug.api) {
|
||||
console.log('[API Client] Refreshing access token...');
|
||||
}
|
||||
|
||||
const { access_token, refresh_token, expires_in } = response.data;
|
||||
// Use generated SDK function for refresh
|
||||
const response = await refreshTokenFn({
|
||||
body: { refresh_token: refreshToken },
|
||||
throwOnError: true,
|
||||
});
|
||||
|
||||
const newAccessToken = response.data.access_token;
|
||||
const newRefreshToken = response.data.refresh_token || refreshToken;
|
||||
|
||||
// Update tokens in store
|
||||
await useAuthStore.getState().setTokens(access_token, refresh_token, expires_in);
|
||||
// Note: Token type from OpenAPI spec doesn't include expires_in,
|
||||
// but backend may return it. We handle both cases gracefully.
|
||||
await authStore.setTokens(
|
||||
newAccessToken,
|
||||
newRefreshToken,
|
||||
undefined // expires_in not in spec, will use default
|
||||
);
|
||||
|
||||
return access_token;
|
||||
if (config.debug.api) {
|
||||
console.log('[API Client] Token refreshed successfully');
|
||||
}
|
||||
|
||||
return newAccessToken;
|
||||
} catch (error) {
|
||||
// Refresh failed - clear auth and redirect
|
||||
console.error('Token refresh failed:', error);
|
||||
await useAuthStore.getState().clearAuth();
|
||||
if (config.debug.api) {
|
||||
console.error('[API Client] Token refresh failed:', error);
|
||||
}
|
||||
|
||||
// Clear auth and redirect to login
|
||||
const authStore = await getAuthStore();
|
||||
await authStore.clearAuth();
|
||||
|
||||
// Redirect to login if we're in browser
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = config.routes.login;
|
||||
const currentPath = window.location.pathname;
|
||||
const returnUrl = currentPath !== '/login' && currentPath !== '/register'
|
||||
? `?returnUrl=${encodeURIComponent(currentPath)}`
|
||||
: '';
|
||||
window.location.href = `/login${returnUrl}`;
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
// Reset refresh state
|
||||
isRefreshing = false;
|
||||
refreshPromise = null;
|
||||
}
|
||||
@@ -102,68 +110,62 @@ async function refreshAccessToken(): Promise<string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Request interceptor - Add authentication token
|
||||
* Request Interceptor
|
||||
* Adds Authorization header with access token to all requests
|
||||
*/
|
||||
apiClient.interceptors.request.use(
|
||||
(requestConfig: InternalAxiosRequestConfig) => {
|
||||
// Get access token from auth store
|
||||
const accessToken = useAuthStore.getState().accessToken;
|
||||
client.instance.interceptors.request.use(
|
||||
async (requestConfig: InternalAxiosRequestConfig) => {
|
||||
const authStore = await getAuthStore();
|
||||
const { accessToken } = authStore;
|
||||
|
||||
// Add Authorization header if token exists
|
||||
if (accessToken) {
|
||||
if (accessToken && requestConfig.headers) {
|
||||
requestConfig.headers.Authorization = `Bearer ${accessToken}`;
|
||||
}
|
||||
|
||||
// Debug logging in development
|
||||
if (config.debug.api) {
|
||||
console.log('🚀 API Request:', {
|
||||
method: requestConfig.method?.toUpperCase(),
|
||||
url: requestConfig.url,
|
||||
hasAuth: !!accessToken,
|
||||
});
|
||||
console.log('[API Client] Request:', requestConfig.method?.toUpperCase(), requestConfig.url);
|
||||
}
|
||||
|
||||
return requestConfig;
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
console.error('Request interceptor error:', error);
|
||||
(error) => {
|
||||
if (config.debug.api) {
|
||||
console.error('[API Client] Request error:', error);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Response interceptor - Handle errors and token refresh
|
||||
* Response Interceptor
|
||||
* Handles errors and token refresh
|
||||
*/
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => {
|
||||
// Debug logging in development
|
||||
client.instance.interceptors.response.use(
|
||||
(response: AxiosResponse) => {
|
||||
if (config.debug.api) {
|
||||
console.log('✅ API Response:', {
|
||||
status: response.status,
|
||||
url: response.config.url,
|
||||
});
|
||||
console.log('[API Client] Response:', response.status, response.config.url);
|
||||
}
|
||||
|
||||
return response;
|
||||
},
|
||||
async (error: AxiosError<APIErrorResponse>) => {
|
||||
const originalRequest = error.config as AxiosRequestConfig & { _retry?: boolean };
|
||||
async (error: AxiosError) => {
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
||||
|
||||
// Debug logging in development
|
||||
if (config.env.isDevelopment) {
|
||||
console.error('❌ API Error:', {
|
||||
status: error.response?.status,
|
||||
url: error.config?.url,
|
||||
message: error.message,
|
||||
});
|
||||
if (config.debug.api) {
|
||||
console.error('[API Client] Response error:', error.response?.status, error.config?.url);
|
||||
}
|
||||
|
||||
// Handle 401 Unauthorized - Token refresh logic
|
||||
// Handle 401 Unauthorized - Token expired
|
||||
if (error.response?.status === 401 && originalRequest && !originalRequest._retry) {
|
||||
// Avoid retrying refresh endpoint itself
|
||||
if (originalRequest.url?.includes('/auth/refresh')) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
// Attempt to refresh token (singleton pattern)
|
||||
// Refresh token
|
||||
const newAccessToken = await refreshAccessToken();
|
||||
|
||||
// Retry original request with new token
|
||||
@@ -171,43 +173,64 @@ apiClient.interceptors.response.use(
|
||||
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
|
||||
}
|
||||
|
||||
return apiClient.request(originalRequest);
|
||||
return client.instance(originalRequest);
|
||||
} catch (refreshError) {
|
||||
// Refresh failed - error already logged, auth cleared
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle 403 Forbidden
|
||||
if (error.response?.status === 403) {
|
||||
console.warn('Access forbidden - insufficient permissions');
|
||||
// Toast notification would be added here in Phase 4
|
||||
if (config.debug.api) {
|
||||
console.warn('[API Client] Access forbidden (403)');
|
||||
}
|
||||
// Let the component handle this (might be permission issue, not auth)
|
||||
}
|
||||
|
||||
// Handle 429 Too Many Requests
|
||||
if (error.response?.status === 429) {
|
||||
const retryAfter = error.response.headers['retry-after'];
|
||||
console.warn(`Rate limit exceeded${retryAfter ? `. Retry after ${retryAfter}s` : ''}`);
|
||||
// Toast notification would be added here in Phase 4
|
||||
if (config.debug.api) {
|
||||
console.warn('[API Client] Rate limit exceeded (429)');
|
||||
}
|
||||
// Add retry-after handling if needed in future
|
||||
}
|
||||
|
||||
// Handle 500+ Server Errors
|
||||
if (error.response?.status && error.response.status >= 500) {
|
||||
console.error('Server error occurred');
|
||||
// Toast notification would be added here in Phase 4
|
||||
if (config.debug.api) {
|
||||
console.error('[API Client] Server error:', error.response.status);
|
||||
}
|
||||
// Could add error tracking service integration here
|
||||
}
|
||||
|
||||
// Handle Network Errors
|
||||
if (!error.response) {
|
||||
console.error('Network error - check your connection');
|
||||
// Toast notification would be added here in Phase 4
|
||||
}
|
||||
|
||||
// Parse and reject with structured error
|
||||
const parsedErrors = parseAPIError(error);
|
||||
return Promise.reject(parsedErrors);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Export default for convenience
|
||||
export default apiClient;
|
||||
/**
|
||||
* Configure the generated client with base settings
|
||||
*/
|
||||
client.setConfig({
|
||||
baseURL: config.api.url,
|
||||
timeout: config.api.timeout,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Configured API client instance
|
||||
* Use this for all API calls
|
||||
*/
|
||||
export { client as apiClient };
|
||||
|
||||
/**
|
||||
* Re-export all SDK functions for convenience
|
||||
* These are already configured with interceptors
|
||||
*/
|
||||
export * from './generated/sdk.gen';
|
||||
|
||||
/**
|
||||
* Re-export types for convenience
|
||||
*/
|
||||
export type * from './generated/types.gen';
|
||||
|
||||
@@ -59,15 +59,42 @@ export const ERROR_MESSAGES: Record<string, string> = {
|
||||
'RATE_LIMIT': 'Too many requests. Please slow down',
|
||||
};
|
||||
|
||||
/**
|
||||
* Type guard to check if error is an AxiosError
|
||||
*/
|
||||
function isAxiosError(error: unknown): error is AxiosError {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'isAxiosError' in error &&
|
||||
(error as any).isAxiosError === true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse API error response
|
||||
* @param error AxiosError from API request
|
||||
* @param error Error from API request (unknown type for flexibility)
|
||||
* @returns Array of structured APIError objects
|
||||
*/
|
||||
export function parseAPIError(error: AxiosError<APIErrorResponse>): APIError[] {
|
||||
export function parseAPIError(error: unknown): APIError[] {
|
||||
// Type guard: check if it's an AxiosError
|
||||
if (!isAxiosError(error)) {
|
||||
// Generic error
|
||||
return [
|
||||
{
|
||||
code: 'UNKNOWN',
|
||||
message: error instanceof Error ? error.message : ERROR_MESSAGES['UNKNOWN'],
|
||||
},
|
||||
];
|
||||
}
|
||||
// Backend structured errors
|
||||
if (error.response?.data?.errors && Array.isArray(error.response.data.errors)) {
|
||||
return error.response.data.errors;
|
||||
if (
|
||||
error.response?.data &&
|
||||
typeof error.response.data === 'object' &&
|
||||
'errors' in error.response.data &&
|
||||
Array.isArray((error.response.data as any).errors)
|
||||
) {
|
||||
return (error.response.data as any).errors;
|
||||
}
|
||||
|
||||
// Network errors (no response)
|
||||
|
||||
@@ -1,60 +1,31 @@
|
||||
/**
|
||||
* Authentication React Query Hooks
|
||||
* Integrates with authStore for state management
|
||||
* Implements all auth endpoints from backend API
|
||||
*
|
||||
* Integrates with auto-generated API client and authStore for state management.
|
||||
* All hooks use generated SDK functions for type safety and OpenAPI compliance.
|
||||
*
|
||||
* @module lib/api/hooks/useAuth
|
||||
*/
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { apiClient } from '../client';
|
||||
import {
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
logoutAll,
|
||||
getCurrentUserInfo,
|
||||
requestPasswordReset,
|
||||
confirmPasswordReset,
|
||||
changeCurrentUserPassword,
|
||||
} from '../client';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import type { User } from '@/stores/authStore';
|
||||
import type { APIError } from '../errors';
|
||||
import { parseAPIError, getGeneralError } from '../errors';
|
||||
import { isTokenWithUser, type TokenWithUser } from '../types';
|
||||
import config from '@/config/app.config';
|
||||
|
||||
// ============================================================================
|
||||
// Types
|
||||
// ============================================================================
|
||||
|
||||
export interface LoginCredentials {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterData {
|
||||
email: string;
|
||||
password: string;
|
||||
first_name: string;
|
||||
last_name?: string;
|
||||
}
|
||||
|
||||
export interface PasswordResetRequest {
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface PasswordResetConfirm {
|
||||
token: string;
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
export interface PasswordChange {
|
||||
current_password: string;
|
||||
new_password: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
access_token: string;
|
||||
refresh_token: string;
|
||||
token_type: 'bearer';
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface SuccessResponse {
|
||||
success: true;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Query Keys
|
||||
// ============================================================================
|
||||
@@ -71,7 +42,11 @@ export const authKeys = {
|
||||
/**
|
||||
* Get current user from token
|
||||
* GET /api/v1/auth/me
|
||||
* Updates auth store with fetched user data
|
||||
*
|
||||
* Automatically syncs user data to auth store when fetched.
|
||||
* Only enabled when user is authenticated with access token.
|
||||
*
|
||||
* @returns React Query result with user data
|
||||
*/
|
||||
export function useMe() {
|
||||
const { isAuthenticated, accessToken } = useAuthStore();
|
||||
@@ -80,8 +55,10 @@ export function useMe() {
|
||||
const query = useQuery({
|
||||
queryKey: authKeys.me,
|
||||
queryFn: async (): Promise<User> => {
|
||||
const response = await apiClient.get<User>('/auth/me');
|
||||
return response.data;
|
||||
const response = await getCurrentUserInfo({
|
||||
throwOnError: true,
|
||||
});
|
||||
return response.data as User;
|
||||
},
|
||||
enabled: isAuthenticated && !!accessToken,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
@@ -105,33 +82,67 @@ export function useMe() {
|
||||
/**
|
||||
* Login mutation
|
||||
* POST /api/v1/auth/login
|
||||
*
|
||||
* On success:
|
||||
* - Stores tokens and user in auth store
|
||||
* - Invalidates auth queries
|
||||
* - Redirects to home page
|
||||
*
|
||||
* @param onSuccess Optional callback after successful login
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function useLogin() {
|
||||
export function useLogin(onSuccess?: () => void) {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const setAuth = useAuthStore((state) => state.setAuth);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (credentials: LoginCredentials): Promise<AuthResponse> => {
|
||||
const response = await apiClient.post<AuthResponse>('/auth/login', credentials);
|
||||
return response.data;
|
||||
mutationFn: async (credentials: { email: string; password: string }) => {
|
||||
const response = await login({
|
||||
body: credentials,
|
||||
throwOnError: false, // Handle errors manually
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
throw response.error;
|
||||
}
|
||||
|
||||
// Type assertion: if no error, response has data
|
||||
const data = (response as { data: unknown }).data;
|
||||
|
||||
// Type guard to ensure response has user data
|
||||
if (!isTokenWithUser(data)) {
|
||||
throw new Error('Invalid login response: missing user data');
|
||||
}
|
||||
|
||||
return data;
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
const { access_token, refresh_token, user } = data;
|
||||
const { access_token, refresh_token, user, expires_in } = data;
|
||||
|
||||
// Update auth store with user and tokens
|
||||
await setAuth(user, access_token, refresh_token);
|
||||
await setAuth(
|
||||
user as User,
|
||||
access_token,
|
||||
refresh_token || '',
|
||||
expires_in
|
||||
);
|
||||
|
||||
// Invalidate and refetch user data
|
||||
queryClient.invalidateQueries({ queryKey: authKeys.all });
|
||||
|
||||
// Call custom success callback if provided
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
}
|
||||
|
||||
// Redirect to home or intended destination
|
||||
// TODO: Add redirect to intended route from query params
|
||||
router.push('/');
|
||||
router.push(config.routes.home);
|
||||
},
|
||||
onError: (errors: APIError[]) => {
|
||||
console.error('Login failed:', errors);
|
||||
// Error toast will be handled in the component
|
||||
onError: (error: unknown) => {
|
||||
const errors = parseAPIError(error);
|
||||
const generalError = getGeneralError(errors);
|
||||
console.error('Login failed:', generalError || 'Unknown error');
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -139,48 +150,115 @@ export function useLogin() {
|
||||
/**
|
||||
* Register mutation
|
||||
* POST /api/v1/auth/register
|
||||
*
|
||||
* On success:
|
||||
* - Stores tokens and user in auth store
|
||||
* - Invalidates auth queries
|
||||
* - Redirects to home page (auto-login)
|
||||
*
|
||||
* @param onSuccess Optional callback after successful registration
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function useRegister() {
|
||||
export function useRegister(onSuccess?: () => void) {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const setAuth = useAuthStore((state) => state.setAuth);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: RegisterData): Promise<AuthResponse> => {
|
||||
const response = await apiClient.post<AuthResponse>('/auth/register', data);
|
||||
return response.data;
|
||||
mutationFn: async (data: {
|
||||
email: string;
|
||||
password: string;
|
||||
first_name: string;
|
||||
last_name?: string;
|
||||
}) => {
|
||||
const response = await register({
|
||||
body: {
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
first_name: data.first_name,
|
||||
last_name: data.last_name || '',
|
||||
},
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
throw response.error;
|
||||
}
|
||||
|
||||
// Type assertion: if no error, response has data
|
||||
const responseData = (response as { data: unknown }).data;
|
||||
|
||||
// Type guard to ensure response has user data
|
||||
if (!isTokenWithUser(responseData)) {
|
||||
throw new Error('Invalid registration response: missing user data');
|
||||
}
|
||||
|
||||
return responseData;
|
||||
},
|
||||
onSuccess: async (data) => {
|
||||
const { access_token, refresh_token, user } = data;
|
||||
const { access_token, refresh_token, user, expires_in } = data;
|
||||
|
||||
// Update auth store with user and tokens
|
||||
await setAuth(user, access_token, refresh_token);
|
||||
// Update auth store with user and tokens (auto-login)
|
||||
await setAuth(
|
||||
user as User,
|
||||
access_token,
|
||||
refresh_token || '',
|
||||
expires_in
|
||||
);
|
||||
|
||||
// Invalidate and refetch user data
|
||||
queryClient.invalidateQueries({ queryKey: authKeys.all });
|
||||
|
||||
// Call custom success callback if provided
|
||||
if (onSuccess) {
|
||||
onSuccess();
|
||||
}
|
||||
|
||||
// Redirect to home
|
||||
router.push('/');
|
||||
router.push(config.routes.home);
|
||||
},
|
||||
onError: (errors: APIError[]) => {
|
||||
console.error('Registration failed:', errors);
|
||||
// Error toast will be handled in the component
|
||||
onError: (error: unknown) => {
|
||||
const errors = parseAPIError(error);
|
||||
const generalError = getGeneralError(errors);
|
||||
console.error('Registration failed:', generalError || 'Unknown error');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout mutation (current device only)
|
||||
* Logout mutation
|
||||
* POST /api/v1/auth/logout
|
||||
*
|
||||
* On success:
|
||||
* - Clears auth store
|
||||
* - Clears React Query cache
|
||||
* - Redirects to login
|
||||
*
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function useLogout() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const clearAuth = useAuthStore((state) => state.clearAuth);
|
||||
const refreshToken = useAuthStore((state) => state.refreshToken);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<SuccessResponse> => {
|
||||
const response = await apiClient.post<SuccessResponse>('/auth/logout');
|
||||
mutationFn: async () => {
|
||||
if (!refreshToken) {
|
||||
// If no refresh token, just clear local state
|
||||
return { success: true, message: 'Logged out locally' };
|
||||
}
|
||||
|
||||
const response = await logout({
|
||||
body: { refresh_token: refreshToken },
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
// Still clear local state even if server logout fails
|
||||
console.warn('Server logout failed, clearing local state anyway');
|
||||
}
|
||||
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: async () => {
|
||||
@@ -193,10 +271,9 @@ export function useLogout() {
|
||||
// Redirect to login
|
||||
router.push(config.routes.login);
|
||||
},
|
||||
onError: async (errors: APIError[]) => {
|
||||
console.error('Logout failed:', errors);
|
||||
|
||||
// Even if logout fails, clear local state
|
||||
onError: async (error: unknown) => {
|
||||
console.error('Logout error:', error);
|
||||
// Still clear auth and redirect even on error
|
||||
await clearAuth();
|
||||
queryClient.clear();
|
||||
router.push(config.routes.login);
|
||||
@@ -205,8 +282,15 @@ export function useLogout() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout all devices mutation
|
||||
* Logout from all devices mutation
|
||||
* POST /api/v1/auth/logout-all
|
||||
*
|
||||
* On success:
|
||||
* - Clears auth store
|
||||
* - Clears React Query cache
|
||||
* - Redirects to login
|
||||
*
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function useLogoutAll() {
|
||||
const router = useRouter();
|
||||
@@ -214,8 +298,16 @@ export function useLogoutAll() {
|
||||
const clearAuth = useAuthStore((state) => state.clearAuth);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (): Promise<SuccessResponse> => {
|
||||
const response = await apiClient.post<SuccessResponse>('/auth/logout-all');
|
||||
mutationFn: async () => {
|
||||
const response = await logoutAll({
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
// Still clear local state even if server logout fails
|
||||
console.warn('Server logout-all failed, clearing local state anyway');
|
||||
}
|
||||
|
||||
return response.data;
|
||||
},
|
||||
onSuccess: async () => {
|
||||
@@ -228,10 +320,9 @@ export function useLogoutAll() {
|
||||
// Redirect to login
|
||||
router.push(config.routes.login);
|
||||
},
|
||||
onError: async (errors: APIError[]) => {
|
||||
console.error('Logout all failed:', errors);
|
||||
|
||||
// Even if logout fails, clear local state
|
||||
onError: async (error: unknown) => {
|
||||
console.error('Logout-all error:', error);
|
||||
// Still clear auth and redirect even on error
|
||||
await clearAuth();
|
||||
queryClient.clear();
|
||||
router.push(config.routes.login);
|
||||
@@ -242,23 +333,44 @@ export function useLogoutAll() {
|
||||
/**
|
||||
* Password reset request mutation
|
||||
* POST /api/v1/auth/password-reset/request
|
||||
*
|
||||
* Sends password reset email to user.
|
||||
*
|
||||
* @param onSuccess Optional callback after successful request
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function usePasswordResetRequest() {
|
||||
export function usePasswordResetRequest(onSuccess?: (message: string) => void) {
|
||||
return useMutation({
|
||||
mutationFn: async (data: PasswordResetRequest): Promise<SuccessResponse> => {
|
||||
const response = await apiClient.post<SuccessResponse>(
|
||||
'/auth/password-reset/request',
|
||||
data
|
||||
);
|
||||
return response.data;
|
||||
mutationFn: async (data: { email: string }) => {
|
||||
const response = await requestPasswordReset({
|
||||
body: data,
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
throw response.error;
|
||||
}
|
||||
|
||||
// Type assertion: if no error, response has data
|
||||
return (response as { data: unknown }).data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
console.log('Password reset email sent:', data.message);
|
||||
// Success toast will be handled in the component
|
||||
const message =
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
'message' in data &&
|
||||
typeof (data as any).message === 'string'
|
||||
? (data as any).message
|
||||
: 'Password reset email sent successfully';
|
||||
|
||||
if (onSuccess) {
|
||||
onSuccess(message);
|
||||
}
|
||||
},
|
||||
onError: (errors: APIError[]) => {
|
||||
console.error('Password reset request failed:', errors);
|
||||
// Error toast will be handled in the component
|
||||
onError: (error: unknown) => {
|
||||
const errors = parseAPIError(error);
|
||||
const generalError = getGeneralError(errors);
|
||||
console.error('Password reset request failed:', generalError || 'Unknown error');
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -266,50 +378,96 @@ export function usePasswordResetRequest() {
|
||||
/**
|
||||
* Password reset confirm mutation
|
||||
* POST /api/v1/auth/password-reset/confirm
|
||||
*
|
||||
* Resets password using token from email.
|
||||
*
|
||||
* @param onSuccess Optional callback after successful reset
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function usePasswordResetConfirm() {
|
||||
export function usePasswordResetConfirm(onSuccess?: (message: string) => void) {
|
||||
const router = useRouter();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (data: PasswordResetConfirm): Promise<SuccessResponse> => {
|
||||
const response = await apiClient.post<SuccessResponse>(
|
||||
'/auth/password-reset/confirm',
|
||||
data
|
||||
);
|
||||
return response.data;
|
||||
mutationFn: async (data: { token: string; new_password: string }) => {
|
||||
const response = await confirmPasswordReset({
|
||||
body: data,
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
throw response.error;
|
||||
}
|
||||
|
||||
// Type assertion: if no error, response has data
|
||||
return (response as { data: unknown }).data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
console.log('Password reset successful:', data.message);
|
||||
// Redirect to login
|
||||
router.push(`${config.routes.login}?reset=success`);
|
||||
const message =
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
'message' in data &&
|
||||
typeof (data as any).message === 'string'
|
||||
? (data as any).message
|
||||
: 'Password reset successful';
|
||||
|
||||
if (onSuccess) {
|
||||
onSuccess(message);
|
||||
}
|
||||
|
||||
// Redirect to login after success
|
||||
setTimeout(() => {
|
||||
router.push(config.routes.login);
|
||||
}, 2000);
|
||||
},
|
||||
onError: (errors: APIError[]) => {
|
||||
console.error('Password reset confirm failed:', errors);
|
||||
// Error toast will be handled in the component
|
||||
onError: (error: unknown) => {
|
||||
const errors = parseAPIError(error);
|
||||
const generalError = getGeneralError(errors);
|
||||
console.error('Password reset failed:', generalError || 'Unknown error');
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Change password mutation (authenticated users)
|
||||
* PATCH /api/v1/users/me/password
|
||||
* Password change mutation (for authenticated users)
|
||||
* POST /api/v1/auth/password/change
|
||||
*
|
||||
* Changes password for currently authenticated user.
|
||||
*
|
||||
* @param onSuccess Optional callback after successful change
|
||||
* @returns React Query mutation
|
||||
*/
|
||||
export function usePasswordChange() {
|
||||
export function usePasswordChange(onSuccess?: (message: string) => void) {
|
||||
return useMutation({
|
||||
mutationFn: async (data: PasswordChange): Promise<SuccessResponse> => {
|
||||
const response = await apiClient.patch<SuccessResponse>(
|
||||
'/users/me/password',
|
||||
data
|
||||
);
|
||||
return response.data;
|
||||
mutationFn: async (data: { current_password: string; new_password: string }) => {
|
||||
const response = await changeCurrentUserPassword({
|
||||
body: data,
|
||||
throwOnError: false,
|
||||
});
|
||||
|
||||
if ('error' in response) {
|
||||
throw response.error;
|
||||
}
|
||||
|
||||
// Type assertion: if no error, response has data
|
||||
return (response as { data: unknown }).data;
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
console.log('Password changed successfully:', data.message);
|
||||
// Success toast will be handled in the component
|
||||
const message =
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
'message' in data &&
|
||||
typeof (data as any).message === 'string'
|
||||
? (data as any).message
|
||||
: 'Password changed successfully';
|
||||
|
||||
if (onSuccess) {
|
||||
onSuccess(message);
|
||||
}
|
||||
},
|
||||
onError: (errors: APIError[]) => {
|
||||
console.error('Password change failed:', errors);
|
||||
// Error toast will be handled in the component
|
||||
onError: (error: unknown) => {
|
||||
const errors = parseAPIError(error);
|
||||
const generalError = getGeneralError(errors);
|
||||
console.error('Password change failed:', generalError || 'Unknown error');
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -320,15 +478,15 @@ export function usePasswordChange() {
|
||||
|
||||
/**
|
||||
* Check if user is authenticated
|
||||
* Convenience hook wrapping auth store
|
||||
* @returns boolean indicating authentication status
|
||||
*/
|
||||
export function useIsAuthenticated(): boolean {
|
||||
return useAuthStore((state) => state.isAuthenticated);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user
|
||||
* Convenience hook wrapping auth store
|
||||
* Get current user from auth store
|
||||
* @returns Current user or null
|
||||
*/
|
||||
export function useCurrentUser(): User | null {
|
||||
return useAuthStore((state) => state.user);
|
||||
@@ -336,6 +494,7 @@ export function useCurrentUser(): User | null {
|
||||
|
||||
/**
|
||||
* Check if current user is admin
|
||||
* @returns boolean indicating admin status
|
||||
*/
|
||||
export function useIsAdmin(): boolean {
|
||||
const user = useCurrentUser();
|
||||
|
||||
62
frontend/src/lib/api/types.ts
Normal file
62
frontend/src/lib/api/types.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Extended API Types
|
||||
*
|
||||
* This file contains type extensions for the auto-generated types when the OpenAPI
|
||||
* spec doesn't fully capture the actual backend response structure.
|
||||
*
|
||||
* @module lib/api/types
|
||||
*/
|
||||
|
||||
import type { Token, UserResponse } from './generated/types.gen';
|
||||
|
||||
/**
|
||||
* Extended Token Response
|
||||
*
|
||||
* The actual backend response includes additional fields not captured in OpenAPI spec:
|
||||
* - user: UserResponse object
|
||||
* - expires_in: Token expiration in seconds
|
||||
*
|
||||
* TODO: Update backend OpenAPI spec to include these fields
|
||||
*/
|
||||
export interface TokenWithUser extends Token {
|
||||
user: UserResponse;
|
||||
expires_in?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Success Response (for operations that return success messages)
|
||||
*/
|
||||
export interface SuccessResponse {
|
||||
success: true;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if response includes user data
|
||||
*/
|
||||
export function isTokenWithUser(token: unknown): token is TokenWithUser {
|
||||
return (
|
||||
typeof token === 'object' &&
|
||||
token !== null &&
|
||||
'access_token' in token &&
|
||||
'user' in token &&
|
||||
typeof (token as any).access_token === 'string' &&
|
||||
typeof (token as any).user === 'object' &&
|
||||
(token as any).user !== null &&
|
||||
!Array.isArray((token as any).user)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Type guard to check if response is a success message
|
||||
*/
|
||||
export function isSuccessResponse(response: unknown): response is SuccessResponse {
|
||||
return (
|
||||
typeof response === 'object' &&
|
||||
response !== null &&
|
||||
'success' in response &&
|
||||
'message' in response &&
|
||||
(response as any).success === true &&
|
||||
typeof (response as any).message === 'string'
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user