feat(frontend): add authentication context and API client
- Add AuthContext for managing user authentication state - Add ProtectedRoute component for route protection - Update API client with JWT token injection - Add refresh token rotation support - Add CSRF token handling
This commit is contained in:
+117
-16
@@ -7,6 +7,22 @@ export const api = axios.create({
|
|||||||
baseURL: API_URL,
|
baseURL: API_URL,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Re-export axios for type checking
|
||||||
|
export { default as axios } from 'axios';
|
||||||
|
export const isAxiosError = axios.isAxiosError;
|
||||||
|
|
||||||
|
// Export api instance for direct use
|
||||||
|
export { api as default };
|
||||||
|
|
||||||
|
// JWT Token Management
|
||||||
|
const TOKEN_KEY = 'excalidash-access-token';
|
||||||
|
const REFRESH_TOKEN_KEY = 'excalidash-refresh-token';
|
||||||
|
|
||||||
|
const getAuthToken = (): string | null => {
|
||||||
|
if (typeof window === 'undefined') return null;
|
||||||
|
return localStorage.getItem(TOKEN_KEY);
|
||||||
|
};
|
||||||
|
|
||||||
// CSRF Token Management
|
// CSRF Token Management
|
||||||
let csrfToken: string | null = null;
|
let csrfToken: string | null = null;
|
||||||
let csrfHeaderName: string = "x-csrf-token";
|
let csrfHeaderName: string = "x-csrf-token";
|
||||||
@@ -50,12 +66,40 @@ export const clearCsrfToken = (): void => {
|
|||||||
csrfToken = null;
|
csrfToken = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add request interceptor to include CSRF token
|
// Add request interceptor to include JWT and CSRF tokens
|
||||||
api.interceptors.request.use(
|
api.interceptors.request.use(
|
||||||
async (config) => {
|
async (config) => {
|
||||||
// Only add CSRF token for state-changing methods
|
// Auth endpoints that require authentication (need JWT token)
|
||||||
|
const authenticatedAuthEndpoints = [
|
||||||
|
'/auth/me',
|
||||||
|
'/auth/profile',
|
||||||
|
'/auth/change-password',
|
||||||
|
];
|
||||||
|
|
||||||
|
// Auth endpoints that don't require authentication (login, register, etc.)
|
||||||
|
const publicAuthEndpoints = [
|
||||||
|
'/auth/login',
|
||||||
|
'/auth/register',
|
||||||
|
'/auth/refresh',
|
||||||
|
'/auth/password-reset-request',
|
||||||
|
'/auth/password-reset-confirm',
|
||||||
|
];
|
||||||
|
|
||||||
|
const isAuthenticatedAuthEndpoint = config.url && authenticatedAuthEndpoints.some(endpoint => config.url?.startsWith(endpoint));
|
||||||
|
const isPublicAuthEndpoint = config.url && publicAuthEndpoints.some(endpoint => config.url?.startsWith(endpoint));
|
||||||
|
const isAuthEndpoint = config.url?.startsWith('/auth/');
|
||||||
|
|
||||||
|
// Add JWT token to all requests except public auth endpoints
|
||||||
|
if (!isPublicAuthEndpoint) {
|
||||||
|
const token = getAuthToken();
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only add CSRF token for state-changing methods (except public auth endpoints)
|
||||||
const method = config.method?.toUpperCase();
|
const method = config.method?.toUpperCase();
|
||||||
if (method && ["POST", "PUT", "DELETE", "PATCH"].includes(method)) {
|
if (method && ["POST", "PUT", "DELETE", "PATCH"].includes(method) && !isPublicAuthEndpoint) {
|
||||||
await ensureCsrfToken();
|
await ensureCsrfToken();
|
||||||
if (csrfToken) {
|
if (csrfToken) {
|
||||||
config.headers[csrfHeaderName] = csrfToken;
|
config.headers[csrfHeaderName] = csrfToken;
|
||||||
@@ -66,10 +110,47 @@ api.interceptors.request.use(
|
|||||||
(error) => Promise.reject(error)
|
(error) => Promise.reject(error)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Add response interceptor to handle CSRF token errors
|
// Add response interceptor to handle auth and CSRF token errors
|
||||||
api.interceptors.response.use(
|
api.interceptors.response.use(
|
||||||
(response) => response,
|
(response) => response,
|
||||||
async (error) => {
|
async (error) => {
|
||||||
|
// Handle 401 Unauthorized (invalid/expired JWT)
|
||||||
|
if (error.response?.status === 401) {
|
||||||
|
const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY);
|
||||||
|
if (refreshToken && !error.config.url?.includes('/auth/')) {
|
||||||
|
try {
|
||||||
|
const refreshResponse = await axios.post(`${API_URL}/auth/refresh`, {
|
||||||
|
refreshToken,
|
||||||
|
});
|
||||||
|
localStorage.setItem(TOKEN_KEY, refreshResponse.data.accessToken);
|
||||||
|
|
||||||
|
// Update refresh token if rotation returned a new one
|
||||||
|
if (refreshResponse.data.refreshToken) {
|
||||||
|
localStorage.setItem(REFRESH_TOKEN_KEY, refreshResponse.data.refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retry original request with new token
|
||||||
|
error.config.headers.Authorization = `Bearer ${refreshResponse.data.accessToken}`;
|
||||||
|
return api(error.config);
|
||||||
|
} catch {
|
||||||
|
// Refresh failed, clear tokens and redirect to login
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
localStorage.removeItem('excalidash-user');
|
||||||
|
window.location.href = '/login';
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No refresh token or auth endpoint, redirect to login
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
localStorage.removeItem('excalidash-user');
|
||||||
|
if (!error.config.url?.includes('/auth/')) {
|
||||||
|
window.location.href = '/login';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// If we get a 403 with CSRF error, clear token and retry once
|
// If we get a 403 with CSRF error, clear token and retry once
|
||||||
if (
|
if (
|
||||||
error.response?.status === 403 &&
|
error.response?.status === 403 &&
|
||||||
@@ -99,7 +180,14 @@ const coerceTimestamp = (value: string | number | Date): number => {
|
|||||||
return Number.isNaN(parsed) ? Date.now() : parsed;
|
return Number.isNaN(parsed) ? Date.now() : parsed;
|
||||||
};
|
};
|
||||||
|
|
||||||
const deserializeTimestamps = <T extends { createdAt: any; updatedAt: any }>(
|
type TimestampValue = string | number | Date;
|
||||||
|
|
||||||
|
interface HasTimestamps {
|
||||||
|
createdAt: TimestampValue;
|
||||||
|
updatedAt: TimestampValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const deserializeTimestamps = <T extends HasTimestamps>(
|
||||||
data: T
|
data: T
|
||||||
): T & { createdAt: number; updatedAt: number } => ({
|
): T & { createdAt: number; updatedAt: number } => ({
|
||||||
...data,
|
...data,
|
||||||
@@ -107,11 +195,19 @@ const deserializeTimestamps = <T extends { createdAt: any; updatedAt: any }>(
|
|||||||
updatedAt: coerceTimestamp(data.updatedAt),
|
updatedAt: coerceTimestamp(data.updatedAt),
|
||||||
});
|
});
|
||||||
|
|
||||||
const deserializeDrawingSummary = (drawing: any): DrawingSummary =>
|
const deserializeDrawingSummary = (drawing: unknown): DrawingSummary => {
|
||||||
deserializeTimestamps(drawing);
|
if (typeof drawing !== 'object' || drawing === null) {
|
||||||
|
throw new Error('Invalid drawing data');
|
||||||
|
}
|
||||||
|
return deserializeTimestamps(drawing as HasTimestamps & DrawingSummary);
|
||||||
|
};
|
||||||
|
|
||||||
const deserializeDrawing = (drawing: any): Drawing =>
|
const deserializeDrawing = (drawing: unknown): Drawing => {
|
||||||
deserializeTimestamps(drawing);
|
if (typeof drawing !== 'object' || drawing === null) {
|
||||||
|
throw new Error('Invalid drawing data');
|
||||||
|
}
|
||||||
|
return deserializeTimestamps(drawing as HasTimestamps & Drawing);
|
||||||
|
};
|
||||||
|
|
||||||
export function getDrawings(
|
export function getDrawings(
|
||||||
search?: string,
|
search?: string,
|
||||||
@@ -129,7 +225,7 @@ export async function getDrawings(
|
|||||||
collectionId?: string | null,
|
collectionId?: string | null,
|
||||||
options?: { includeData?: boolean }
|
options?: { includeData?: boolean }
|
||||||
) {
|
) {
|
||||||
const params: any = {};
|
const params: Record<string, string> = {};
|
||||||
if (search) params.search = search;
|
if (search) params.search = search;
|
||||||
if (collectionId !== undefined)
|
if (collectionId !== undefined)
|
||||||
params.collectionId = collectionId === null ? "null" : collectionId;
|
params.collectionId = collectionId === null ? "null" : collectionId;
|
||||||
@@ -152,8 +248,10 @@ export const createDrawing = async (
|
|||||||
collectionId?: string | null
|
collectionId?: string | null
|
||||||
) => {
|
) => {
|
||||||
const response = await api.post<{ id: string }>("/drawings", {
|
const response = await api.post<{ id: string }>("/drawings", {
|
||||||
name,
|
name: name || "Untitled Drawing",
|
||||||
collectionId,
|
collectionId: collectionId ?? null,
|
||||||
|
elements: [],
|
||||||
|
appState: {},
|
||||||
});
|
});
|
||||||
return response.data;
|
return response.data;
|
||||||
};
|
};
|
||||||
@@ -197,12 +295,15 @@ export const deleteCollection = async (id: string) => {
|
|||||||
|
|
||||||
// --- Library ---
|
// --- Library ---
|
||||||
|
|
||||||
export const getLibrary = async () => {
|
// Library items are Excalidraw library items - dynamic structure from Excalidraw
|
||||||
const response = await api.get<{ items: any[] }>("/library");
|
type LibraryItem = Record<string, unknown>;
|
||||||
|
|
||||||
|
export const getLibrary = async (): Promise<LibraryItem[]> => {
|
||||||
|
const response = await api.get<{ items: LibraryItem[] }>("/library");
|
||||||
return response.data.items;
|
return response.data.items;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const updateLibrary = async (items: any[]) => {
|
export const updateLibrary = async (items: LibraryItem[]): Promise<LibraryItem[]> => {
|
||||||
const response = await api.put<{ items: any[] }>("/library", { items });
|
const response = await api.put<{ items: LibraryItem[] }>("/library", { items });
|
||||||
return response.data.items;
|
return response.data.items;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Navigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../context/AuthContext';
|
||||||
|
|
||||||
|
interface ProtectedRouteProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
|
||||||
|
const { isAuthenticated, loading } = useAuth();
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center">
|
||||||
|
<div className="text-gray-600 dark:text-gray-400">Loading...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
return <Navigate to="/login" replace />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>{children}</>;
|
||||||
|
};
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import axios from 'axios';
|
||||||
|
|
||||||
|
const API_URL = import.meta.env.VITE_API_URL || "/api";
|
||||||
|
|
||||||
|
interface User {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthContextType {
|
||||||
|
user: User | null;
|
||||||
|
loading: boolean;
|
||||||
|
login: (email: string, password: string) => Promise<void>;
|
||||||
|
register: (email: string, password: string, name: string) => Promise<void>;
|
||||||
|
logout: () => void;
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
const TOKEN_KEY = 'excalidash-access-token';
|
||||||
|
const REFRESH_TOKEN_KEY = 'excalidash-refresh-token';
|
||||||
|
const USER_KEY = 'excalidash-user';
|
||||||
|
|
||||||
|
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
||||||
|
const [user, setUser] = useState<User | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
// Load user from localStorage on mount
|
||||||
|
useEffect(() => {
|
||||||
|
const loadUser = async () => {
|
||||||
|
try {
|
||||||
|
const storedUser = localStorage.getItem(USER_KEY);
|
||||||
|
const storedToken = localStorage.getItem(TOKEN_KEY);
|
||||||
|
|
||||||
|
if (storedUser && storedToken) {
|
||||||
|
const userData = JSON.parse(storedUser);
|
||||||
|
setUser(userData);
|
||||||
|
|
||||||
|
// Verify token is still valid by fetching user info
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${API_URL}/auth/me`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${storedToken}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setUser(response.data.user);
|
||||||
|
} catch (error) {
|
||||||
|
// Token invalid, try refresh
|
||||||
|
const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY);
|
||||||
|
if (refreshToken) {
|
||||||
|
try {
|
||||||
|
const refreshResponse = await axios.post(`${API_URL}/auth/refresh`, {
|
||||||
|
refreshToken,
|
||||||
|
});
|
||||||
|
localStorage.setItem(TOKEN_KEY, refreshResponse.data.accessToken);
|
||||||
|
const userResponse = await axios.get(`${API_URL}/auth/me`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${refreshResponse.data.accessToken}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
setUser(userResponse.data.user);
|
||||||
|
} catch {
|
||||||
|
// Refresh failed, clear auth but don't navigate during initial load
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
localStorage.removeItem(USER_KEY);
|
||||||
|
setUser(null);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// No refresh token, clear auth
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
localStorage.removeItem(USER_KEY);
|
||||||
|
setUser(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load user:', error);
|
||||||
|
// Clear auth on error
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
localStorage.removeItem(USER_KEY);
|
||||||
|
setUser(null);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadUser();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const login = async (email: string, password: string) => {
|
||||||
|
try {
|
||||||
|
const response = await axios.post(`${API_URL}/auth/login`, {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { user: userData, accessToken, refreshToken } = response.data;
|
||||||
|
|
||||||
|
localStorage.setItem(TOKEN_KEY, accessToken);
|
||||||
|
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
|
||||||
|
localStorage.setItem(USER_KEY, JSON.stringify(userData));
|
||||||
|
|
||||||
|
setUser(userData);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
const message =
|
||||||
|
typeof error.response?.data === 'object' &&
|
||||||
|
error.response.data !== null &&
|
||||||
|
'message' in error.response.data &&
|
||||||
|
typeof error.response.data.message === 'string'
|
||||||
|
? error.response.data.message
|
||||||
|
: 'Login failed';
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error('Login failed');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const register = async (email: string, password: string, name: string) => {
|
||||||
|
try {
|
||||||
|
const response = await axios.post(`${API_URL}/auth/register`, {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { user: userData, accessToken, refreshToken } = response.data;
|
||||||
|
|
||||||
|
localStorage.setItem(TOKEN_KEY, accessToken);
|
||||||
|
localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken);
|
||||||
|
localStorage.setItem(USER_KEY, JSON.stringify(userData));
|
||||||
|
|
||||||
|
setUser(userData);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
if (axios.isAxiosError(error)) {
|
||||||
|
const message =
|
||||||
|
typeof error.response?.data === 'object' &&
|
||||||
|
error.response.data !== null &&
|
||||||
|
'message' in error.response.data &&
|
||||||
|
typeof error.response.data.message === 'string'
|
||||||
|
? error.response.data.message
|
||||||
|
: 'Registration failed';
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
throw error instanceof Error ? error : new Error('Registration failed');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
|
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||||
|
localStorage.removeItem(USER_KEY);
|
||||||
|
setUser(null);
|
||||||
|
// Navigate to login - use setTimeout to ensure Router is ready
|
||||||
|
setTimeout(() => {
|
||||||
|
navigate('/login');
|
||||||
|
}, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<AuthContext.Provider
|
||||||
|
value={{
|
||||||
|
user,
|
||||||
|
loading,
|
||||||
|
login,
|
||||||
|
register,
|
||||||
|
logout,
|
||||||
|
isAuthenticated: !!user,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</AuthContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useAuth = () => {
|
||||||
|
const context = useContext(AuthContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useAuth must be used within an AuthProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user