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