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:
@@ -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')
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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('*');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<PaginatedResult<KycQueueItem> | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -172,28 +170,27 @@ export default function AdminKycPage() {
|
||||
const [actionError, setActionError] = useState<string | null>(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);
|
||||
|
||||
@@ -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<PaginatedResult<ModerationQueueItem> | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(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,
|
||||
|
||||
@@ -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<DashboardStats | null>(null);
|
||||
const [revenue, setRevenue] = useState<RevenueStatsItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(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();
|
||||
|
||||
@@ -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<PaginatedResult<UserListItem> | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -189,11 +187,10 @@ export default function AdminUsersPage() {
|
||||
const [actionError, setActionError] = useState<string | null>(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
|
||||
|
||||
@@ -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()}
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
Đăng xuất
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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}</>;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
|
||||
@@ -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 }),
|
||||
};
|
||||
|
||||
@@ -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'),
|
||||
};
|
||||
|
||||
@@ -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();
|
||||
},
|
||||
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user