From 6389dcf78efbf16ffd499383622a678df9a0d771 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Wed, 8 Apr 2026 06:25:11 +0700 Subject: [PATCH] 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 --- .../controllers/auth.controller.ts | 23 ++++- .../presentation/dto/refresh-token.dto.ts | 9 +- apps/api/src/modules/shared/shared.module.ts | 9 +- apps/web/app/(admin)/admin/kyc/page.tsx | 15 ++-- .../web/app/(admin)/admin/moderation/page.tsx | 18 ++-- apps/web/app/(admin)/admin/page.tsx | 9 +- apps/web/app/(admin)/admin/users/page.tsx | 13 +-- apps/web/app/(admin)/layout.tsx | 2 +- apps/web/app/(dashboard)/layout.tsx | 2 +- .../web/app/(dashboard)/listings/new/page.tsx | 11 +-- apps/web/app/(dashboard)/listings/page.tsx | 3 - apps/web/app/auth/callback/google/page.tsx | 6 +- apps/web/app/auth/callback/zalo/page.tsx | 6 +- .../components/providers/auth-provider.tsx | 13 --- apps/web/lib/admin-api.ts | 56 ++++++------ apps/web/lib/api-client.ts | 16 +--- apps/web/lib/auth-api.ts | 28 +++--- apps/web/lib/auth-store.ts | 90 +++++++------------ apps/web/lib/listings-api.ts | 13 ++- 19 files changed, 151 insertions(+), 191 deletions(-) diff --git a/apps/api/src/modules/auth/presentation/controllers/auth.controller.ts b/apps/api/src/modules/auth/presentation/controllers/auth.controller.ts index 9476cc4..1edd4dd 100644 --- a/apps/api/src/modules/auth/presentation/controllers/auth.controller.ts +++ b/apps/api/src/modules/auth/presentation/controllers/auth.controller.ts @@ -28,7 +28,7 @@ import { LocalAuthGuard } from '../guards/local-auth.guard'; import { RolesGuard } from '../guards/roles.guard'; import { CurrentUser } from '../decorators/current-user.decorator'; import { Roles } from '../decorators/roles.decorator'; -import { type JwtPayload, type TokenPair } from '../../infrastructure/services/token.service'; +import { TokenService, type JwtPayload, type TokenPair } from '../../infrastructure/services/token.service'; import { type UserProfileDto } from '../../application/queries/get-profile/get-profile.handler'; import { type AgentDto } from '../../application/queries/get-agent-by-user-id/get-agent-by-user-id.handler'; @@ -73,6 +73,7 @@ export class AuthController { constructor( private readonly commandBus: CommandBus, private readonly queryBus: QueryBus, + private readonly tokenService: TokenService, ) {} @Throttle({ default: { ttl: 3_600_000, limit: 5 }, auth: { ttl: 3_600_000, limit: 5 } }) @@ -140,6 +141,26 @@ export class AuthController { return { message: 'Đã đăng xuất' }; } + @Post('exchange-token') + @ApiOperation({ summary: 'Exchange OAuth token pair for httpOnly cookies' }) + @ApiResponse({ status: 201, description: 'Auth cookies set' }) + @ApiResponse({ status: 401, description: 'Invalid access token' }) + async exchangeToken( + @Body() body: { accessToken: string; refreshToken: string; expiresIn?: number }, + @Res({ passthrough: true }) res: Response, + ): Promise<{ message: string }> { + const payload = this.tokenService.verifyAccessToken(body.accessToken); + if (!payload) { + throw new UnauthorizedException('Invalid access token'); + } + setAuthCookies(res, { + accessToken: body.accessToken, + refreshToken: body.refreshToken, + expiresIn: body.expiresIn ?? 900, + }); + return { message: 'Auth cookies set' }; + } + @UseGuards(JwtAuthGuard) @Get('profile') @ApiBearerAuth('JWT') diff --git a/apps/api/src/modules/auth/presentation/dto/refresh-token.dto.ts b/apps/api/src/modules/auth/presentation/dto/refresh-token.dto.ts index c4049f1..b786fdb 100644 --- a/apps/api/src/modules/auth/presentation/dto/refresh-token.dto.ts +++ b/apps/api/src/modules/auth/presentation/dto/refresh-token.dto.ts @@ -1,8 +1,9 @@ -import { IsString } from 'class-validator'; -import { ApiProperty } from '@nestjs/swagger'; +import { IsOptional, IsString } from 'class-validator'; +import { ApiPropertyOptional } from '@nestjs/swagger'; export class RefreshTokenDto { - @ApiProperty({ description: 'JWT refresh token' }) + @ApiPropertyOptional({ description: 'JWT refresh token (optional if sent via cookie)' }) + @IsOptional() @IsString() - refreshToken!: string; + refreshToken?: string; } diff --git a/apps/api/src/modules/shared/shared.module.ts b/apps/api/src/modules/shared/shared.module.ts index 787c091..a5e10f9 100644 --- a/apps/api/src/modules/shared/shared.module.ts +++ b/apps/api/src/modules/shared/shared.module.ts @@ -48,7 +48,14 @@ export class SharedModule implements NestModule { if (process.env['NODE_ENV'] !== 'test') { consumer .apply(CsrfMiddleware) - .exclude({ path: 'payments/callback/(.*)', method: RequestMethod.POST }) + .exclude( + { path: 'payments/callback/(.*)', method: RequestMethod.POST }, + { path: 'auth/login', method: RequestMethod.POST }, + { path: 'auth/register', method: RequestMethod.POST }, + { path: 'auth/refresh', method: RequestMethod.POST }, + { path: 'auth/exchange-token', method: RequestMethod.POST }, + { path: 'auth/logout', method: RequestMethod.POST }, + ) .forRoutes('*'); } } diff --git a/apps/web/app/(admin)/admin/kyc/page.tsx b/apps/web/app/(admin)/admin/kyc/page.tsx index 38f34a4..43b89e7 100644 --- a/apps/web/app/(admin)/admin/kyc/page.tsx +++ b/apps/web/app/(admin)/admin/kyc/page.tsx @@ -24,7 +24,6 @@ import { DialogDescription, DialogFooter, } from '@/components/ui/dialog'; -import { useAuthStore } from '@/lib/auth-store'; import { adminApi, type KycQueueItem, type PaginatedResult } from '@/lib/admin-api'; function kycStatusBadge(status: string) { @@ -152,7 +151,6 @@ function KycDetailView({ item, onApprove, onReject }: { } export default function AdminKycPage() { - const { tokens } = useAuthStore(); const [result, setResult] = useState | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -172,28 +170,27 @@ export default function AdminKycPage() { const [actionError, setActionError] = useState(null); const fetchQueue = useCallback(async () => { - if (!tokens?.accessToken) return; setLoading(true); setError(null); try { - const data = await adminApi.getKycQueue(tokens.accessToken, page, 20); + const data = await adminApi.getKycQueue(page, 20); setResult(data); } catch (e) { setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi KYC'); } finally { setLoading(false); } - }, [tokens?.accessToken, page]); + }, [page]); useEffect(() => { fetchQueue(); }, [fetchQueue]); const handleApprove = async () => { - if (!tokens?.accessToken || !approveDialog) return; + if (!approveDialog) return; setActionLoading(true); try { - await adminApi.approveKyc(tokens.accessToken, approveDialog, approveNotes || undefined); + await adminApi.approveKyc(approveDialog, approveNotes || undefined); setApproveDialog(null); setApproveNotes(''); setSelectedItem(null); @@ -206,10 +203,10 @@ export default function AdminKycPage() { }; const handleReject = async () => { - if (!tokens?.accessToken || !rejectDialog || !rejectReason.trim()) return; + if (!rejectDialog || !rejectReason.trim()) return; setActionLoading(true); try { - await adminApi.rejectKyc(tokens.accessToken, rejectDialog, rejectReason); + await adminApi.rejectKyc(rejectDialog, rejectReason); setRejectDialog(null); setRejectReason(''); setSelectedItem(null); diff --git a/apps/web/app/(admin)/admin/moderation/page.tsx b/apps/web/app/(admin)/admin/moderation/page.tsx index 3ae8e1b..44043b6 100644 --- a/apps/web/app/(admin)/admin/moderation/page.tsx +++ b/apps/web/app/(admin)/admin/moderation/page.tsx @@ -23,7 +23,6 @@ import { DialogDescription, DialogFooter, } from '@/components/ui/dialog'; -import { useAuthStore } from '@/lib/auth-store'; import { adminApi, type ModerationQueueItem, type PaginatedResult } from '@/lib/admin-api'; function formatPrice(price: number): string { @@ -44,7 +43,6 @@ function moderationScoreBadge(score: number | null) { } export default function AdminModerationPage() { - const { tokens } = useAuthStore(); const [result, setResult] = useState | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -66,28 +64,27 @@ export default function AdminModerationPage() { const [bulkReason, setBulkReason] = useState(''); const fetchQueue = useCallback(async () => { - if (!tokens?.accessToken) return; setLoading(true); setError(null); try { - const data = await adminApi.getModerationQueue(tokens.accessToken, page, 20); + const data = await adminApi.getModerationQueue(page, 20); setResult(data); } catch (e) { setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi'); } finally { setLoading(false); } - }, [tokens?.accessToken, page]); + }, [page]); useEffect(() => { fetchQueue(); }, [fetchQueue]); const handleApprove = async () => { - if (!tokens?.accessToken || !approveDialog) return; + if (!approveDialog) return; setActionLoading(true); try { - await adminApi.approveListing(tokens.accessToken, approveDialog, approveNotes || undefined); + await adminApi.approveListing(approveDialog, approveNotes || undefined); setApproveDialog(null); setApproveNotes(''); fetchQueue(); @@ -99,10 +96,10 @@ export default function AdminModerationPage() { }; const handleReject = async () => { - if (!tokens?.accessToken || !rejectDialog || !rejectReason.trim()) return; + if (!rejectDialog || !rejectReason.trim()) return; setActionLoading(true); try { - await adminApi.rejectListing(tokens.accessToken, rejectDialog, rejectReason); + await adminApi.rejectListing(rejectDialog, rejectReason); setRejectDialog(null); setRejectReason(''); fetchQueue(); @@ -114,11 +111,10 @@ export default function AdminModerationPage() { }; const handleBulkAction = async () => { - if (!tokens?.accessToken || !bulkAction || selected.size === 0) return; + if (!bulkAction || selected.size === 0) return; setActionLoading(true); try { await adminApi.bulkModerate( - tokens.accessToken, Array.from(selected), bulkAction, bulkReason || undefined, diff --git a/apps/web/app/(admin)/admin/page.tsx b/apps/web/app/(admin)/admin/page.tsx index 70d2d9c..47fa35c 100644 --- a/apps/web/app/(admin)/admin/page.tsx +++ b/apps/web/app/(admin)/admin/page.tsx @@ -15,7 +15,6 @@ import { } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; -import { useAuthStore } from '@/lib/auth-store'; import { adminApi, type DashboardStats, type RevenueStatsItem } from '@/lib/admin-api'; interface StatCardProps { @@ -95,14 +94,12 @@ function RevenueChart({ data }: { data: RevenueStatsItem[] }) { } export default function AdminDashboardPage() { - const { tokens } = useAuthStore(); const [stats, setStats] = useState(null); const [revenue, setRevenue] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const fetchData = useCallback(async () => { - if (!tokens?.accessToken) return; setLoading(true); setError(null); try { @@ -110,8 +107,8 @@ export default function AdminDashboardPage() { const startDate = new Date(Date.now() - 180 * 86400000).toISOString().split('T')[0]!; const [statsData, revenueData] = await Promise.all([ - adminApi.getDashboardStats(tokens.accessToken), - adminApi.getRevenueStats(tokens.accessToken, startDate, endDate, 'month'), + adminApi.getDashboardStats(), + adminApi.getRevenueStats(startDate, endDate, 'month'), ]); setStats(statsData); setRevenue(revenueData); @@ -120,7 +117,7 @@ export default function AdminDashboardPage() { } finally { setLoading(false); } - }, [tokens?.accessToken]); + }, []); useEffect(() => { fetchData(); diff --git a/apps/web/app/(admin)/admin/users/page.tsx b/apps/web/app/(admin)/admin/users/page.tsx index 0271f2b..c284654 100644 --- a/apps/web/app/(admin)/admin/users/page.tsx +++ b/apps/web/app/(admin)/admin/users/page.tsx @@ -25,7 +25,6 @@ import { DialogDescription, DialogFooter, } from '@/components/ui/dialog'; -import { useAuthStore } from '@/lib/auth-store'; import { adminApi, type UserListItem, @@ -169,7 +168,6 @@ function UserDetailPanel({ } export default function AdminUsersPage() { - const { tokens } = useAuthStore(); const [result, setResult] = useState | null>(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); @@ -189,11 +187,10 @@ export default function AdminUsersPage() { const [actionError, setActionError] = useState(null); const fetchUsers = useCallback(async () => { - if (!tokens?.accessToken) return; setLoading(true); setError(null); try { - const data = await adminApi.getUsers(tokens.accessToken, { + const data = await adminApi.getUsers({ page, limit: 20, role: roleFilter || undefined, @@ -206,17 +203,16 @@ export default function AdminUsersPage() { } finally { setLoading(false); } - }, [tokens?.accessToken, page, roleFilter, statusFilter, search]); + }, [page, roleFilter, statusFilter, search]); useEffect(() => { fetchUsers(); }, [fetchUsers]); const openDetail = async (userId: string) => { - if (!tokens?.accessToken) return; setDetailLoading(true); try { - const detail = await adminApi.getUserDetail(tokens.accessToken, userId); + const detail = await adminApi.getUserDetail(userId); setSelectedUser(detail); } catch (e) { setActionError(e instanceof Error ? e.message : 'Không thể tải chi tiết người dùng'); @@ -231,11 +227,10 @@ export default function AdminUsersPage() { }; const confirmToggleStatus = async () => { - if (!tokens?.accessToken || !banDialog) return; + if (!banDialog) return; setActionLoading(true); try { await adminApi.banUser( - tokens.accessToken, banDialog.userId, banReason || 'Admin action', banDialog.isActive, // unban = true if making active diff --git a/apps/web/app/(admin)/layout.tsx b/apps/web/app/(admin)/layout.tsx index 9fb870a..ab41183 100644 --- a/apps/web/app/(admin)/layout.tsx +++ b/apps/web/app/(admin)/layout.tsx @@ -114,7 +114,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode }) variant="ghost" size="sm" className="w-full justify-start gap-2" - onClick={logout} + onClick={() => logout()} > Đăng xuất diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsx index 0d7c500..998133c 100644 --- a/apps/web/app/(dashboard)/layout.tsx +++ b/apps/web/app/(dashboard)/layout.tsx @@ -49,7 +49,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod {user.fullName} )} - diff --git a/apps/web/app/(dashboard)/listings/new/page.tsx b/apps/web/app/(dashboard)/listings/new/page.tsx index 4454a2f..9b59fc9 100644 --- a/apps/web/app/(dashboard)/listings/new/page.tsx +++ b/apps/web/app/(dashboard)/listings/new/page.tsx @@ -22,7 +22,6 @@ import { type CreateListingFormData, } from '@/lib/validations/listings'; import { listingsApi, type CreateListingPayload, type Direction } from '@/lib/listings-api'; -import { useAuthStore } from '@/lib/auth-store'; import { cn } from '@/lib/utils'; const STEPS = [ @@ -41,7 +40,6 @@ function toNum(val: string | undefined): number | undefined { export default function CreateListingPage() { const router = useRouter(); - const { tokens } = useAuthStore(); const [currentStep, setCurrentStep] = React.useState(0); const [images, setImages] = React.useState([]); const [isSubmitting, setIsSubmitting] = React.useState(false); @@ -69,11 +67,6 @@ export default function CreateListingPage() { const goBack = () => setCurrentStep((s) => Math.max(s - 1, 0)); const onSubmit = async (data: CreateListingFormData) => { - if (!tokens?.accessToken) { - setError('Vui lòng đăng nhập để đăng tin'); - return; - } - setIsSubmitting(true); setError(null); @@ -117,11 +110,11 @@ export default function CreateListingPage() { const commissionPct = toNum(data.commissionPct); if (commissionPct != null) payload.commissionPct = commissionPct; - const result = await listingsApi.create(tokens.accessToken, payload); + const result = await listingsApi.create(payload); for (const img of images) { try { - await listingsApi.uploadMedia(tokens.accessToken, result.listingId, img.file); + await listingsApi.uploadMedia(result.listingId, img.file); } catch { // Continue with remaining images } diff --git a/apps/web/app/(dashboard)/listings/page.tsx b/apps/web/app/(dashboard)/listings/page.tsx index b129885..f11d697 100644 --- a/apps/web/app/(dashboard)/listings/page.tsx +++ b/apps/web/app/(dashboard)/listings/page.tsx @@ -15,8 +15,6 @@ import { type PaginatedResult, } from '@/lib/listings-api'; import { PROPERTY_TYPES, TRANSACTION_TYPES, LISTING_STATUSES } from '@/lib/validations/listings'; -import { useAuthStore } from '@/lib/auth-store'; - function formatPrice(priceVND: string): string { const num = Number(priceVND); if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} ty`; @@ -36,7 +34,6 @@ function formatDate(dateStr: string | null): string { type ViewMode = 'grid' | 'table'; export default function ListingsPage() { - const { tokens } = useAuthStore(); const [result, setResult] = React.useState | null>(null); const [loading, setLoading] = React.useState(true); const [viewMode, setViewMode] = React.useState('grid'); diff --git a/apps/web/app/auth/callback/google/page.tsx b/apps/web/app/auth/callback/google/page.tsx index 381beb7..4966a60 100644 --- a/apps/web/app/auth/callback/google/page.tsx +++ b/apps/web/app/auth/callback/google/page.tsx @@ -30,11 +30,11 @@ export default function GoogleCallbackPage() { return; } - handleOAuthCallback({ + handleOAuthCallback( accessToken, refreshToken, - expiresIn: expiresIn ? Number(expiresIn) : 900, - }) + expiresIn ? Number(expiresIn) : 900, + ) .then(() => { const redirect = searchParams.get('redirect') || '/dashboard'; router.replace(redirect); diff --git a/apps/web/app/auth/callback/zalo/page.tsx b/apps/web/app/auth/callback/zalo/page.tsx index 4994ffe..31de2ac 100644 --- a/apps/web/app/auth/callback/zalo/page.tsx +++ b/apps/web/app/auth/callback/zalo/page.tsx @@ -30,11 +30,11 @@ export default function ZaloCallbackPage() { return; } - handleOAuthCallback({ + handleOAuthCallback( accessToken, refreshToken, - expiresIn: expiresIn ? Number(expiresIn) : 900, - }) + expiresIn ? Number(expiresIn) : 900, + ) .then(() => { const redirect = searchParams.get('redirect') || '/dashboard'; router.replace(redirect); diff --git a/apps/web/components/providers/auth-provider.tsx b/apps/web/components/providers/auth-provider.tsx index 9328543..1a2b4e2 100644 --- a/apps/web/components/providers/auth-provider.tsx +++ b/apps/web/components/providers/auth-provider.tsx @@ -3,25 +3,12 @@ import { useEffect } from 'react'; import { useAuthStore } from '@/lib/auth-store'; -function setAuthCookie(authenticated: boolean) { - if (authenticated) { - document.cookie = 'goodgo_authenticated=1; path=/; max-age=604800; SameSite=Lax'; - } else { - document.cookie = 'goodgo_authenticated=; path=/; max-age=0'; - } -} - export function AuthProvider({ children }: { children: React.ReactNode }) { const initialize = useAuthStore((s) => s.initialize); - const tokens = useAuthStore((s) => s.tokens); useEffect(() => { initialize(); }, [initialize]); - useEffect(() => { - setAuthCookie(!!tokens); - }, [tokens]); - return <>{children}; } diff --git a/apps/web/lib/admin-api.ts b/apps/web/lib/admin-api.ts index 0b5eb32..0ae41ee 100644 --- a/apps/web/lib/admin-api.ts +++ b/apps/web/lib/admin-api.ts @@ -96,87 +96,83 @@ export interface KycQueueItem { export const adminApi = { // Dashboard - getDashboardStats: (token: string) => - apiClient.authGet('/admin/dashboard', token), + getDashboardStats: () => + apiClient.get('/admin/dashboard'), - getRevenueStats: (token: string, startDate: string, endDate: string, groupBy: 'day' | 'month' = 'month') => - apiClient.authGet( + getRevenueStats: (startDate: string, endDate: string, groupBy: 'day' | 'month' = 'month') => + apiClient.get( `/admin/revenue?startDate=${startDate}&endDate=${endDate}&groupBy=${groupBy}`, - token, ), // Moderation - getModerationQueue: (token: string, page = 1, limit = 20) => - apiClient.authGet>( + getModerationQueue: (page = 1, limit = 20) => + apiClient.get>( `/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>( + return apiClient.get>( `/admin/users?${query.toString()}`, - token, ); }, - getUserDetail: (token: string, userId: string) => - apiClient.authGet(`/admin/users/${userId}`, token), + getUserDetail: (userId: string) => + apiClient.get(`/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>( + getKycQueue: (page = 1, limit = 20) => + apiClient.get>( `/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, }), diff --git a/apps/web/lib/api-client.ts b/apps/web/lib/api-client.ts index 9e51841..5235194 100644 --- a/apps/web/lib/api-client.ts +++ b/apps/web/lib/api-client.ts @@ -17,7 +17,7 @@ type RequestOptions = Omit & { 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(endpoint: string, options: RequestOptions = {}): Promi return res.json(); } -function authHeaders(token: string): HeadersInit { - return { Authorization: `Bearer ${token}` }; -} - export const apiClient = { get: (endpoint: string, headers?: HeadersInit) => request(endpoint, { method: 'GET', headers }), @@ -67,12 +63,6 @@ export const apiClient = { patch: (endpoint: string, body?: unknown, headers?: HeadersInit) => request(endpoint, { method: 'PATCH', body, headers }), - authGet: (endpoint: string, token: string) => - request(endpoint, { method: 'GET', headers: authHeaders(token) }), - - authPost: (endpoint: string, token: string, body?: unknown) => - request(endpoint, { method: 'POST', body, headers: authHeaders(token) }), - - authPatch: (endpoint: string, token: string, body?: unknown) => - request(endpoint, { method: 'PATCH', body, headers: authHeaders(token) }), + delete: (endpoint: string, headers?: HeadersInit) => + request(endpoint, { method: 'DELETE', headers }), }; diff --git a/apps/web/lib/auth-api.ts b/apps/web/lib/auth-api.ts index 81afa2c..99153d6 100644 --- a/apps/web/lib/auth-api.ts +++ b/apps/web/lib/auth-api.ts @@ -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('/auth/register', data), + register: (data: RegisterPayload) => + apiClient.post<{ message: string }>('/auth/register', data), - login: (data: LoginPayload) => apiClient.post('/auth/login', data), + login: (data: LoginPayload) => + apiClient.post<{ message: string }>('/auth/login', data), - refresh: (refreshToken: string) => - apiClient.post('/auth/refresh', { refreshToken }), + refresh: () => + apiClient.post<{ message: string }>('/auth/refresh'), - getProfile: (token: string) => apiClient.authGet('/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('/auth/profile'), }; diff --git a/apps/web/lib/auth-store.ts b/apps/web/lib/auth-store.ts index 5ae3ebb..9c1cde5 100644 --- a/apps/web/lib/auth-store.ts +++ b/apps/web/lib/auth-store.ts @@ -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; register: (data: RegisterPayload) => Promise; - handleOAuthCallback: (tokens: TokenPair) => Promise; - logout: () => void; + handleOAuthCallback: (accessToken: string, refreshToken: string, expiresIn?: number) => Promise; + logout: () => Promise; refreshToken: () => Promise; fetchProfile: () => Promise; initialize: () => Promise; @@ -43,17 +24,16 @@ interface AuthState { } export const useAuthStore = create((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((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((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((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((set, get) => ({ }, initialize: async () => { - const tokens = loadTokens(); - if (!tokens) return; - set({ tokens }); + if (!hasAuthCookie()) return; + set({ isAuthenticated: true }); await get().fetchProfile(); }, diff --git a/apps/web/lib/listings-api.ts b/apps/web/lib/listings-api.ts index 4faca16..6f9d1d5 100644 --- a/apps/web/lib/listings-api.ts +++ b/apps/web/lib/listings-api.ts @@ -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>(`/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, });