security: implementa auth HttpOnly Cookie e atualiza frontend para credentials:include

This commit is contained in:
GoHorse Deploy 2026-03-07 19:39:18 -03:00
parent e182d53eca
commit 31dabed7b9
2 changed files with 84 additions and 1037 deletions

File diff suppressed because it is too large Load diff

View file

@ -35,34 +35,24 @@ async function getErrorMessage(response: Response): Promise<string> {
/** /**
* Generic API Request Wrapper * Generic API Request Wrapper
* Configured for HTTP-Only Cookie Authentication
*/ */
async function apiRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> { async function apiRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const token = typeof window !== 'undefined' ? (localStorage.getItem("auth_token") || localStorage.getItem("token")) : null;
const headers: Record<string, string> = { const headers: Record<string, string> = {
"Content-Type": "application/json", "Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options.headers as Record<string, string>, ...options.headers as Record<string, string>,
}; };
if (options.body) {
headers["Content-Type"] = "application/json";
}
const response = await fetch(`${getApiUrl()}${endpoint}`, { const response = await fetch(`${getApiUrl()}${endpoint}`, {
...options, ...options,
headers, headers,
// Crucial for HTTP-Only Cookies
credentials: "include", credentials: "include",
}); });
if (!response.ok) { if (!response.ok) {
// Handle 401 silently - it's expected for unauthenticated users
if (response.status === 401) { if (response.status === 401) {
// Clear any stale auth data // No need to clear localStorage, cookies are managed by browser
if (typeof window !== 'undefined') {
localStorage.removeItem("job-portal-auth");
}
// Throw a specific error that can be caught and handled silently
const error = new Error('Unauthorized'); const error = new Error('Unauthorized');
(error as any).status = 401; (error as any).status = 401;
(error as any).silent = true; (error as any).silent = true;
@ -101,16 +91,16 @@ export interface ApiJob {
companyLogoUrl?: string; companyLogoUrl?: string;
companyId: string; companyId: string;
location?: string | null; location?: string | null;
type?: string; // Legacy alias type?: string;
employmentType?: string; employmentType?: string;
workMode?: string | null; // "remote", etc. workMode?: string | null;
salaryMin?: number; salaryMin?: number;
salaryMax?: number; salaryMax?: number;
salaryType?: string; salaryType?: string;
currency?: string; currency?: string;
description: string; description: string;
requirements?: unknown; requirements?: unknown;
questions?: { items?: JobQuestion[] }; // Custom application questions questions?: { items?: JobQuestion[] };
status: string; status: string;
createdAt: string; createdAt: string;
datePosted?: string; datePosted?: string;
@ -237,6 +227,11 @@ export const authApi = {
body: JSON.stringify(data), body: JSON.stringify(data),
}); });
}, },
logout: () => {
return apiRequest<any>("/api/v1/auth/logout", {
method: "POST"
});
},
register: (data: any) => { register: (data: any) => {
logCrudAction("register", "auth", { email: data.email }); logCrudAction("register", "auth", { email: data.email });
return apiRequest<any>("/api/v1/auth/register", { return apiRequest<any>("/api/v1/auth/register", {
@ -526,7 +521,7 @@ export const jobsApi = {
body: JSON.stringify({ active }), body: JSON.stringify({ active }),
}), }),
// Favorites - wrap with silent error handling // Favorites
getFavorites: () => apiRequest<Array<{ getFavorites: () => apiRequest<Array<{
id: string; id: string;
jobId: string; jobId: string;
@ -620,8 +615,6 @@ export const storageApi = {
), ),
uploadFile: async (file: File, folder = "uploads") => { uploadFile: async (file: File, folder = "uploads") => {
const token = typeof window !== 'undefined' ? (localStorage.getItem("auth_token") || localStorage.getItem("token")) : null;
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
formData.append('folder', folder); formData.append('folder', folder);
@ -629,9 +622,7 @@ export const storageApi = {
const response = await fetch(`${getApiUrl()}/api/v1/storage/upload`, { const response = await fetch(`${getApiUrl()}/api/v1/storage/upload`, {
method: 'POST', method: 'POST',
body: formData, body: formData,
headers: { // Cookies will be sent automatically
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
credentials: 'include', credentials: 'include',
}); });
@ -831,18 +822,11 @@ export const profileApi = {
// ============================================================================= // =============================================================================
async function backofficeRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> { async function backofficeRequest<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const token = typeof window !== 'undefined' ? (localStorage.getItem("auth_token") || localStorage.getItem("token")) : null;
const headers: Record<string, string> = { const headers: Record<string, string> = {
"Content-Type": "application/json", "Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options.headers as Record<string, string>, ...options.headers as Record<string, string>,
}; };
if (options.body) {
headers["Content-Type"] = "application/json";
}
const response = await fetch(`${getBackofficeUrl()}${endpoint}`, { const response = await fetch(`${getBackofficeUrl()}${endpoint}`, {
...options, ...options,
headers, headers,