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

@@ -49,7 +49,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
{user.fullName}
</span>
)}
<Button variant="ghost" size="sm" onClick={logout}>
<Button variant="ghost" size="sm" onClick={() => logout()}>
Đăng xuất
</Button>
</div>

View File

@@ -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<ImageFile[]>([]);
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
}

View File

@@ -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<PaginatedResult<ListingDetail> | null>(null);
const [loading, setLoading] = React.useState(true);
const [viewMode, setViewMode] = React.useState<ViewMode>('grid');