Files
goodgo-platform/apps/web/lib/auth-store.ts
Ho Ngoc Hai 6389dcf78e 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>
2026-04-08 06:25:11 +07:00

118 lines
3.3 KiB
TypeScript

import { create } from 'zustand';
import { authApi, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
import { ApiError } from './api-client';
function hasAuthCookie(): boolean {
if (typeof document === 'undefined') return false;
return document.cookie.includes('goodgo_authenticated=1');
}
interface AuthState {
user: UserProfile | null;
isAuthenticated: boolean;
isLoading: boolean;
error: string | null;
login: (data: LoginPayload) => Promise<void>;
register: (data: RegisterPayload) => Promise<void>;
handleOAuthCallback: (accessToken: string, refreshToken: string, expiresIn?: number) => Promise<void>;
logout: () => Promise<void>;
refreshToken: () => Promise<boolean>;
fetchProfile: () => Promise<void>;
initialize: () => Promise<void>;
clearError: () => void;
}
export const useAuthStore = create<AuthState>((set, get) => ({
user: null,
isAuthenticated: false,
isLoading: false,
error: null,
login: async (data) => {
set({ isLoading: true, error: null });
try {
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';
set({ isLoading: false, error: message });
throw e;
}
},
register: async (data) => {
set({ isLoading: true, error: null });
try {
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';
set({ isLoading: false, error: message });
throw e;
}
},
handleOAuthCallback: async (accessToken, refreshToken, expiresIn) => {
set({ isLoading: true, error: null });
try {
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';
set({ isLoading: false, error: message });
throw e;
}
},
logout: async () => {
try {
await authApi.logout();
} catch {
// Clear state even if API call fails
}
set({ user: null, isAuthenticated: false, error: null });
},
refreshToken: async () => {
try {
await authApi.refresh();
set({ isAuthenticated: true });
return true;
} catch {
set({ user: null, isAuthenticated: false });
return false;
}
},
fetchProfile: async () => {
try {
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) {
try {
const user = await authApi.getProfile();
set({ user, isAuthenticated: true });
} catch {
set({ user: null, isAuthenticated: false });
}
}
}
}
},
initialize: async () => {
if (!hasAuthCookie()) return;
set({ isAuthenticated: true });
await get().fetchProfile();
},
clearError: () => set({ error: null }),
}));