- Log when saveToken is called with token details - Log when request interceptor checks for token - Log when Authorization header is set or token is missing - Helps diagnose 401 Unauthorized issues after login
87 lines
1.9 KiB
TypeScript
87 lines
1.9 KiB
TypeScript
/**
|
|
* [C-01] JWT Authentication Utilities
|
|
* Handle token storage, retrieval, and expiration
|
|
*/
|
|
|
|
const TOKEN_KEY = 'inventory_token';
|
|
const USER_KEY = 'inventory_user';
|
|
|
|
export interface AuthToken {
|
|
access_token: string;
|
|
token_type: string;
|
|
user_id: number;
|
|
username: string;
|
|
role: string;
|
|
}
|
|
|
|
export interface AuthUser {
|
|
id: number;
|
|
username: string;
|
|
role: string;
|
|
}
|
|
|
|
/**
|
|
* Save JWT token to localStorage
|
|
*/
|
|
export const saveToken = (token: AuthToken): void => {
|
|
console.log('[Auth] saveToken called with token:', {
|
|
access_token: token.access_token?.substring(0, 20) + '...',
|
|
user_id: token.user_id,
|
|
username: token.username,
|
|
role: token.role
|
|
});
|
|
localStorage.setItem(TOKEN_KEY, token.access_token);
|
|
localStorage.setItem(USER_KEY, JSON.stringify({
|
|
id: token.user_id,
|
|
username: token.username,
|
|
role: token.role
|
|
}));
|
|
console.log('[Auth] Token saved to localStorage. TOKEN_KEY:', TOKEN_KEY);
|
|
};
|
|
|
|
/**
|
|
* Get JWT token from localStorage
|
|
*/
|
|
export const getToken = (): string | null => {
|
|
if (typeof window === 'undefined') return null;
|
|
return localStorage.getItem(TOKEN_KEY);
|
|
};
|
|
|
|
/**
|
|
* Get current user info from localStorage
|
|
*/
|
|
export const getCurrentUser = (): AuthUser | null => {
|
|
if (typeof window === 'undefined') return null;
|
|
const userJson = localStorage.getItem(USER_KEY);
|
|
if (!userJson) return null;
|
|
try {
|
|
return JSON.parse(userJson);
|
|
} catch {
|
|
return null;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Check if user is authenticated (token exists)
|
|
*/
|
|
export const isAuthenticated = (): boolean => {
|
|
return !!getToken();
|
|
};
|
|
|
|
/**
|
|
* Clear token and user data (logout)
|
|
*/
|
|
export const clearAuth = (): void => {
|
|
localStorage.removeItem(TOKEN_KEY);
|
|
localStorage.removeItem(USER_KEY);
|
|
};
|
|
|
|
/**
|
|
* Get Bearer token for API requests
|
|
*/
|
|
export const getAuthHeader = (): { Authorization: string } | {} => {
|
|
const token = getToken();
|
|
if (!token) return {};
|
|
return { Authorization: `Bearer ${token}` };
|
|
};
|