fix(auth): migrate tokens from localStorage to httpOnly cookies + CSRF hardening

Backend:
- Auth controller sets httpOnly secure cookies (access_token, refresh_token, goodgo_authenticated) on login/register/refresh
- JWT strategy reads token from cookie first, falls back to Authorization header
- Added POST /auth/logout to clear auth cookies
- Added POST /auth/exchange-token for OAuth callback token-to-cookie exchange
- Refresh endpoint reads refresh_token from cookie (body fallback for backwards compat)
- CSRF middleware excludes auth endpoints (login, register, refresh, exchange-token, logout)

Frontend:
- Removed all localStorage token storage (goodgo_tokens key)
- Removed authGet/authPost/authPatch helpers from api-client (tokens sent via cookies)
- All API calls use credentials:'include' for cookie-based auth
- Updated auth-store: no more token state, uses isAuthenticated flag from cookie
- Updated admin-api, listings-api to remove explicit token parameters
- Updated all pages (admin dashboard, users, KYC, moderation, listings) to remove token passing
- OAuth callbacks use exchange-token endpoint to convert URL tokens to cookies
- Auth provider simplified (no client-side cookie management needed)

Security improvements:
- JWT no longer accessible via JavaScript (XSS-safe)
- Refresh token scoped to /auth path only
- Server-side goodgo_authenticated cookie with SameSite=Lax
- Access token cookie with SameSite=Strict

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 06:25:11 +07:00
parent 9583d1cb66
commit 6389dcf78e
19 changed files with 151 additions and 191 deletions

View File

@@ -96,87 +96,83 @@ export interface KycQueueItem {
export const adminApi = {
// Dashboard
getDashboardStats: (token: string) =>
apiClient.authGet<DashboardStats>('/admin/dashboard', token),
getDashboardStats: () =>
apiClient.get<DashboardStats>('/admin/dashboard'),
getRevenueStats: (token: string, startDate: string, endDate: string, groupBy: 'day' | 'month' = 'month') =>
apiClient.authGet<RevenueStatsItem[]>(
getRevenueStats: (startDate: string, endDate: string, groupBy: 'day' | 'month' = 'month') =>
apiClient.get<RevenueStatsItem[]>(
`/admin/revenue?startDate=${startDate}&endDate=${endDate}&groupBy=${groupBy}`,
token,
),
// Moderation
getModerationQueue: (token: string, page = 1, limit = 20) =>
apiClient.authGet<PaginatedResult<ModerationQueueItem>>(
getModerationQueue: (page = 1, limit = 20) =>
apiClient.get<PaginatedResult<ModerationQueueItem>>(
`/admin/moderation?page=${page}&limit=${limit}`,
token,
),
approveListing: (token: string, listingId: string, moderationNotes?: string) =>
apiClient.authPost<{ success: boolean }>('/admin/moderation/approve', token, {
approveListing: (listingId: string, moderationNotes?: string) =>
apiClient.post<{ success: boolean }>('/admin/moderation/approve', {
listingId,
moderationNotes,
}),
rejectListing: (token: string, listingId: string, reason: string) =>
apiClient.authPost<{ success: boolean }>('/admin/moderation/reject', token, {
rejectListing: (listingId: string, reason: string) =>
apiClient.post<{ success: boolean }>('/admin/moderation/reject', {
listingId,
reason,
}),
bulkModerate: (token: string, listingIds: string[], action: 'approve' | 'reject', reason?: string) =>
apiClient.authPost<{ success: boolean }>('/admin/moderation/bulk', token, {
bulkModerate: (listingIds: string[], action: 'approve' | 'reject', reason?: string) =>
apiClient.post<{ success: boolean }>('/admin/moderation/bulk', {
listingIds,
action,
reason,
}),
// Users
getUsers: (token: string, params: { page?: number; limit?: number; role?: string; isActive?: boolean; search?: string } = {}) => {
getUsers: (params: { page?: number; limit?: number; role?: string; isActive?: boolean; search?: string } = {}) => {
const query = new URLSearchParams();
if (params.page) query.set('page', String(params.page));
if (params.limit) query.set('limit', String(params.limit));
if (params.role) query.set('role', params.role);
if (params.isActive !== undefined) query.set('isActive', String(params.isActive));
if (params.search) query.set('search', params.search);
return apiClient.authGet<PaginatedResult<UserListItem>>(
return apiClient.get<PaginatedResult<UserListItem>>(
`/admin/users?${query.toString()}`,
token,
);
},
getUserDetail: (token: string, userId: string) =>
apiClient.authGet<UserDetail>(`/admin/users/${userId}`, token),
getUserDetail: (userId: string) =>
apiClient.get<UserDetail>(`/admin/users/${userId}`),
updateUserStatus: (token: string, userId: string, isActive: boolean, reason?: string) =>
apiClient.authPost<{ success: boolean }>('/admin/users/status', token, {
updateUserStatus: (userId: string, isActive: boolean, reason?: string) =>
apiClient.post<{ success: boolean }>('/admin/users/status', {
userId,
isActive,
reason,
}),
banUser: (token: string, userId: string, reason: string, unban = false) =>
apiClient.authPost<{ success: boolean }>('/admin/users/ban', token, {
banUser: (userId: string, reason: string, unban = false) =>
apiClient.post<{ success: boolean }>('/admin/users/ban', {
userId,
reason,
unban,
}),
// KYC
getKycQueue: (token: string, page = 1, limit = 20) =>
apiClient.authGet<PaginatedResult<KycQueueItem>>(
getKycQueue: (page = 1, limit = 20) =>
apiClient.get<PaginatedResult<KycQueueItem>>(
`/admin/kyc?page=${page}&limit=${limit}`,
token,
),
approveKyc: (token: string, userId: string, notes?: string) =>
apiClient.authPost<{ success: boolean }>('/admin/kyc/approve', token, {
approveKyc: (userId: string, notes?: string) =>
apiClient.post<{ success: boolean }>('/admin/kyc/approve', {
userId,
notes,
}),
rejectKyc: (token: string, userId: string, reason: string) =>
apiClient.authPost<{ success: boolean }>('/admin/kyc/reject', token, {
rejectKyc: (userId: string, reason: string) =>
apiClient.post<{ success: boolean }>('/admin/kyc/reject', {
userId,
reason,
}),

View File

@@ -17,7 +17,7 @@ type RequestOptions = Omit<RequestInit, 'body'> & {
function getCsrfToken(): string | undefined {
if (typeof document === 'undefined') return undefined;
const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]*)/);
return match ? decodeURIComponent(match[1]) : undefined;
return match?.[1] ? decodeURIComponent(match[1]) : undefined;
}
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
@@ -53,10 +53,6 @@ async function request<T>(endpoint: string, options: RequestOptions = {}): Promi
return res.json();
}
function authHeaders(token: string): HeadersInit {
return { Authorization: `Bearer ${token}` };
}
export const apiClient = {
get: <T>(endpoint: string, headers?: HeadersInit) =>
request<T>(endpoint, { method: 'GET', headers }),
@@ -67,12 +63,6 @@ export const apiClient = {
patch: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
request<T>(endpoint, { method: 'PATCH', body, headers }),
authGet: <T>(endpoint: string, token: string) =>
request<T>(endpoint, { method: 'GET', headers: authHeaders(token) }),
authPost: <T>(endpoint: string, token: string, body?: unknown) =>
request<T>(endpoint, { method: 'POST', body, headers: authHeaders(token) }),
authPatch: <T>(endpoint: string, token: string, body?: unknown) =>
request<T>(endpoint, { method: 'PATCH', body, headers: authHeaders(token) }),
delete: <T>(endpoint: string, headers?: HeadersInit) =>
request<T>(endpoint, { method: 'DELETE', headers }),
};

View File

@@ -1,11 +1,5 @@
import { apiClient } from './api-client';
export interface TokenPair {
accessToken: string;
refreshToken: string;
expiresIn: number;
}
export interface UserProfile {
id: string;
email: string | null;
@@ -31,12 +25,24 @@ export interface LoginPayload {
}
export const authApi = {
register: (data: RegisterPayload) => apiClient.post<TokenPair>('/auth/register', data),
register: (data: RegisterPayload) =>
apiClient.post<{ message: string }>('/auth/register', data),
login: (data: LoginPayload) => apiClient.post<TokenPair>('/auth/login', data),
login: (data: LoginPayload) =>
apiClient.post<{ message: string }>('/auth/login', data),
refresh: (refreshToken: string) =>
apiClient.post<TokenPair>('/auth/refresh', { refreshToken }),
refresh: () =>
apiClient.post<{ message: string }>('/auth/refresh'),
getProfile: (token: string) => apiClient.authGet<UserProfile>('/auth/profile', token),
logout: () =>
apiClient.post<{ message: string }>('/auth/logout'),
exchangeToken: (accessToken: string, refreshToken: string, expiresIn?: number) =>
apiClient.post<{ message: string }>('/auth/exchange-token', {
accessToken,
refreshToken,
expiresIn,
}),
getProfile: () => apiClient.get<UserProfile>('/auth/profile'),
};

View File

@@ -1,41 +1,22 @@
import { create } from 'zustand';
import { authApi, type TokenPair, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
import { authApi, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
import { ApiError } from './api-client';
export type { TokenPair };
const TOKEN_KEY = 'goodgo_tokens';
function persistTokens(tokens: TokenPair | null) {
if (typeof window === 'undefined') return;
if (tokens) {
localStorage.setItem(TOKEN_KEY, JSON.stringify(tokens));
} else {
localStorage.removeItem(TOKEN_KEY);
}
}
function loadTokens(): TokenPair | null {
if (typeof window === 'undefined') return null;
const raw = localStorage.getItem(TOKEN_KEY);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
return null;
}
function hasAuthCookie(): boolean {
if (typeof document === 'undefined') return false;
return document.cookie.includes('goodgo_authenticated=1');
}
interface AuthState {
tokens: TokenPair | null;
user: UserProfile | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
login: (data: LoginPayload) => Promise<void>;
register: (data: RegisterPayload) => Promise<void>;
handleOAuthCallback: (tokens: TokenPair) => Promise<void>;
logout: () => void;
handleOAuthCallback: (accessToken: string, refreshToken: string, expiresIn?: number) => Promise<void>;
logout: () => Promise<void>;
refreshToken: () => Promise<boolean>;
fetchProfile: () => Promise<void>;
initialize: () => Promise<void>;
@@ -43,17 +24,16 @@ interface AuthState {
}
export const useAuthStore = create<AuthState>((set, get) => ({
tokens: null,
user: null,
isAuthenticated: false,
isLoading: false,
error: null,
login: async (data) => {
set({ isLoading: true, error: null });
try {
const tokens = await authApi.login(data);
persistTokens(tokens);
set({ tokens, isLoading: false });
await authApi.login(data);
set({ isAuthenticated: true, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng nhập thất bại';
@@ -65,9 +45,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
register: async (data) => {
set({ isLoading: true, error: null });
try {
const tokens = await authApi.register(data);
persistTokens(tokens);
set({ tokens, isLoading: false });
await authApi.register(data);
set({ isAuthenticated: true, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng ký thất bại';
@@ -76,11 +55,11 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}
},
handleOAuthCallback: async (tokens) => {
handleOAuthCallback: async (accessToken, refreshToken, expiresIn) => {
set({ isLoading: true, error: null });
try {
persistTokens(tokens);
set({ tokens, isLoading: false });
await authApi.exchangeToken(accessToken, refreshToken, expiresIn);
set({ isAuthenticated: true, isLoading: false });
await get().fetchProfile();
} catch (e) {
const message = e instanceof ApiError ? e.message : 'Đăng nhập OAuth thất bại';
@@ -89,39 +68,39 @@ export const useAuthStore = create<AuthState>((set, get) => ({
}
},
logout: () => {
persistTokens(null);
set({ tokens: null, user: null, error: null });
logout: async () => {
try {
await authApi.logout();
} catch {
// Clear state even if API call fails
}
set({ user: null, isAuthenticated: false, error: null });
},
refreshToken: async () => {
const { tokens } = get();
if (!tokens?.refreshToken) return false;
try {
const newTokens = await authApi.refresh(tokens.refreshToken);
persistTokens(newTokens);
set({ tokens: newTokens });
await authApi.refresh();
set({ isAuthenticated: true });
return true;
} catch {
get().logout();
set({ user: null, isAuthenticated: false });
return false;
}
},
fetchProfile: async () => {
const { tokens } = get();
if (!tokens?.accessToken) return;
try {
const user = await authApi.getProfile(tokens.accessToken);
set({ user });
const user = await authApi.getProfile();
set({ user, isAuthenticated: true });
} catch (e) {
if (e instanceof ApiError && e.status === 401) {
const refreshed = await get().refreshToken();
if (refreshed) {
const newTokens = get().tokens;
if (newTokens) {
const user = await authApi.getProfile(newTokens.accessToken);
set({ user });
try {
const user = await authApi.getProfile();
set({ user, isAuthenticated: true });
} catch {
set({ user: null, isAuthenticated: false });
}
}
}
@@ -129,9 +108,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
},
initialize: async () => {
const tokens = loadTokens();
if (!tokens) return;
set({ tokens });
if (!hasAuthCookie()) return;
set({ isAuthenticated: true });
await get().fetchProfile();
},

View File

@@ -134,10 +134,9 @@ export interface SearchListingsParams {
const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001';
export const listingsApi = {
create: (token: string, data: CreateListingPayload) =>
apiClient.authPost<{ listingId: string; propertyId: string; status: string }>(
create: (data: CreateListingPayload) =>
apiClient.post<{ listingId: string; propertyId: string; status: string }>(
'/listings',
token,
data,
),
@@ -152,20 +151,20 @@ export const listingsApi = {
return apiClient.get<PaginatedResult<ListingDetail>>(`/listings${qs ? `?${qs}` : ''}`);
},
updateStatus: (token: string, id: string, status: ListingStatus, moderationNotes?: string) =>
apiClient.authPost<{ status: string }>(`/listings/${id}/status`, token, {
updateStatus: (id: string, status: ListingStatus, moderationNotes?: string) =>
apiClient.post<{ status: string }>(`/listings/${id}/status`, {
status,
moderationNotes,
}),
uploadMedia: async (token: string, listingId: string, file: File, caption?: string) => {
uploadMedia: async (listingId: string, file: File, caption?: string) => {
const formData = new FormData();
formData.append('file', file);
if (caption) formData.append('caption', caption);
const res = await fetch(`${API_BASE_URL}/listings/${listingId}/media`, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
credentials: 'include',
body: formData,
});