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 { RolesGuard } from '../guards/roles.guard';
|
||||||
import { CurrentUser } from '../decorators/current-user.decorator';
|
import { CurrentUser } from '../decorators/current-user.decorator';
|
||||||
import { Roles } from '../decorators/roles.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 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';
|
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(
|
constructor(
|
||||||
private readonly commandBus: CommandBus,
|
private readonly commandBus: CommandBus,
|
||||||
private readonly queryBus: QueryBus,
|
private readonly queryBus: QueryBus,
|
||||||
|
private readonly tokenService: TokenService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Throttle({ default: { ttl: 3_600_000, limit: 5 }, auth: { ttl: 3_600_000, limit: 5 } })
|
@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' };
|
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)
|
@UseGuards(JwtAuthGuard)
|
||||||
@Get('profile')
|
@Get('profile')
|
||||||
@ApiBearerAuth('JWT')
|
@ApiBearerAuth('JWT')
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { IsString } from 'class-validator';
|
import { IsOptional, IsString } from 'class-validator';
|
||||||
import { ApiProperty } from '@nestjs/swagger';
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
|
||||||
export class RefreshTokenDto {
|
export class RefreshTokenDto {
|
||||||
@ApiProperty({ description: 'JWT refresh token' })
|
@ApiPropertyOptional({ description: 'JWT refresh token (optional if sent via cookie)' })
|
||||||
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
refreshToken!: string;
|
refreshToken?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,7 +48,14 @@ export class SharedModule implements NestModule {
|
|||||||
if (process.env['NODE_ENV'] !== 'test') {
|
if (process.env['NODE_ENV'] !== 'test') {
|
||||||
consumer
|
consumer
|
||||||
.apply(CsrfMiddleware)
|
.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('*');
|
.forRoutes('*');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ import {
|
|||||||
DialogDescription,
|
DialogDescription,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
import { adminApi, type KycQueueItem, type PaginatedResult } from '@/lib/admin-api';
|
import { adminApi, type KycQueueItem, type PaginatedResult } from '@/lib/admin-api';
|
||||||
|
|
||||||
function kycStatusBadge(status: string) {
|
function kycStatusBadge(status: string) {
|
||||||
@@ -152,7 +151,6 @@ function KycDetailView({ item, onApprove, onReject }: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function AdminKycPage() {
|
export default function AdminKycPage() {
|
||||||
const { tokens } = useAuthStore();
|
|
||||||
const [result, setResult] = useState<PaginatedResult<KycQueueItem> | null>(null);
|
const [result, setResult] = useState<PaginatedResult<KycQueueItem> | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -172,28 +170,27 @@ export default function AdminKycPage() {
|
|||||||
const [actionError, setActionError] = useState<string | null>(null);
|
const [actionError, setActionError] = useState<string | null>(null);
|
||||||
|
|
||||||
const fetchQueue = useCallback(async () => {
|
const fetchQueue = useCallback(async () => {
|
||||||
if (!tokens?.accessToken) return;
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data = await adminApi.getKycQueue(tokens.accessToken, page, 20);
|
const data = await adminApi.getKycQueue(page, 20);
|
||||||
setResult(data);
|
setResult(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi KYC');
|
setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi KYC');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [tokens?.accessToken, page]);
|
}, [page]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchQueue();
|
fetchQueue();
|
||||||
}, [fetchQueue]);
|
}, [fetchQueue]);
|
||||||
|
|
||||||
const handleApprove = async () => {
|
const handleApprove = async () => {
|
||||||
if (!tokens?.accessToken || !approveDialog) return;
|
if (!approveDialog) return;
|
||||||
setActionLoading(true);
|
setActionLoading(true);
|
||||||
try {
|
try {
|
||||||
await adminApi.approveKyc(tokens.accessToken, approveDialog, approveNotes || undefined);
|
await adminApi.approveKyc(approveDialog, approveNotes || undefined);
|
||||||
setApproveDialog(null);
|
setApproveDialog(null);
|
||||||
setApproveNotes('');
|
setApproveNotes('');
|
||||||
setSelectedItem(null);
|
setSelectedItem(null);
|
||||||
@@ -206,10 +203,10 @@ export default function AdminKycPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleReject = async () => {
|
const handleReject = async () => {
|
||||||
if (!tokens?.accessToken || !rejectDialog || !rejectReason.trim()) return;
|
if (!rejectDialog || !rejectReason.trim()) return;
|
||||||
setActionLoading(true);
|
setActionLoading(true);
|
||||||
try {
|
try {
|
||||||
await adminApi.rejectKyc(tokens.accessToken, rejectDialog, rejectReason);
|
await adminApi.rejectKyc(rejectDialog, rejectReason);
|
||||||
setRejectDialog(null);
|
setRejectDialog(null);
|
||||||
setRejectReason('');
|
setRejectReason('');
|
||||||
setSelectedItem(null);
|
setSelectedItem(null);
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ import {
|
|||||||
DialogDescription,
|
DialogDescription,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
import { adminApi, type ModerationQueueItem, type PaginatedResult } from '@/lib/admin-api';
|
import { adminApi, type ModerationQueueItem, type PaginatedResult } from '@/lib/admin-api';
|
||||||
|
|
||||||
function formatPrice(price: number): string {
|
function formatPrice(price: number): string {
|
||||||
@@ -44,7 +43,6 @@ function moderationScoreBadge(score: number | null) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function AdminModerationPage() {
|
export default function AdminModerationPage() {
|
||||||
const { tokens } = useAuthStore();
|
|
||||||
const [result, setResult] = useState<PaginatedResult<ModerationQueueItem> | null>(null);
|
const [result, setResult] = useState<PaginatedResult<ModerationQueueItem> | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -66,28 +64,27 @@ export default function AdminModerationPage() {
|
|||||||
const [bulkReason, setBulkReason] = useState('');
|
const [bulkReason, setBulkReason] = useState('');
|
||||||
|
|
||||||
const fetchQueue = useCallback(async () => {
|
const fetchQueue = useCallback(async () => {
|
||||||
if (!tokens?.accessToken) return;
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data = await adminApi.getModerationQueue(tokens.accessToken, page, 20);
|
const data = await adminApi.getModerationQueue(page, 20);
|
||||||
setResult(data);
|
setResult(data);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi');
|
setError(e instanceof Error ? e.message : 'Không thể tải hàng đợi');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [tokens?.accessToken, page]);
|
}, [page]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchQueue();
|
fetchQueue();
|
||||||
}, [fetchQueue]);
|
}, [fetchQueue]);
|
||||||
|
|
||||||
const handleApprove = async () => {
|
const handleApprove = async () => {
|
||||||
if (!tokens?.accessToken || !approveDialog) return;
|
if (!approveDialog) return;
|
||||||
setActionLoading(true);
|
setActionLoading(true);
|
||||||
try {
|
try {
|
||||||
await adminApi.approveListing(tokens.accessToken, approveDialog, approveNotes || undefined);
|
await adminApi.approveListing(approveDialog, approveNotes || undefined);
|
||||||
setApproveDialog(null);
|
setApproveDialog(null);
|
||||||
setApproveNotes('');
|
setApproveNotes('');
|
||||||
fetchQueue();
|
fetchQueue();
|
||||||
@@ -99,10 +96,10 @@ export default function AdminModerationPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleReject = async () => {
|
const handleReject = async () => {
|
||||||
if (!tokens?.accessToken || !rejectDialog || !rejectReason.trim()) return;
|
if (!rejectDialog || !rejectReason.trim()) return;
|
||||||
setActionLoading(true);
|
setActionLoading(true);
|
||||||
try {
|
try {
|
||||||
await adminApi.rejectListing(tokens.accessToken, rejectDialog, rejectReason);
|
await adminApi.rejectListing(rejectDialog, rejectReason);
|
||||||
setRejectDialog(null);
|
setRejectDialog(null);
|
||||||
setRejectReason('');
|
setRejectReason('');
|
||||||
fetchQueue();
|
fetchQueue();
|
||||||
@@ -114,11 +111,10 @@ export default function AdminModerationPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleBulkAction = async () => {
|
const handleBulkAction = async () => {
|
||||||
if (!tokens?.accessToken || !bulkAction || selected.size === 0) return;
|
if (!bulkAction || selected.size === 0) return;
|
||||||
setActionLoading(true);
|
setActionLoading(true);
|
||||||
try {
|
try {
|
||||||
await adminApi.bulkModerate(
|
await adminApi.bulkModerate(
|
||||||
tokens.accessToken,
|
|
||||||
Array.from(selected),
|
Array.from(selected),
|
||||||
bulkAction,
|
bulkAction,
|
||||||
bulkReason || undefined,
|
bulkReason || undefined,
|
||||||
|
|||||||
@@ -15,7 +15,6 @@ import {
|
|||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
import { adminApi, type DashboardStats, type RevenueStatsItem } from '@/lib/admin-api';
|
import { adminApi, type DashboardStats, type RevenueStatsItem } from '@/lib/admin-api';
|
||||||
|
|
||||||
interface StatCardProps {
|
interface StatCardProps {
|
||||||
@@ -95,14 +94,12 @@ function RevenueChart({ data }: { data: RevenueStatsItem[] }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function AdminDashboardPage() {
|
export default function AdminDashboardPage() {
|
||||||
const { tokens } = useAuthStore();
|
|
||||||
const [stats, setStats] = useState<DashboardStats | null>(null);
|
const [stats, setStats] = useState<DashboardStats | null>(null);
|
||||||
const [revenue, setRevenue] = useState<RevenueStatsItem[]>([]);
|
const [revenue, setRevenue] = useState<RevenueStatsItem[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
const fetchData = useCallback(async () => {
|
||||||
if (!tokens?.accessToken) return;
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
@@ -110,8 +107,8 @@ export default function AdminDashboardPage() {
|
|||||||
const startDate = new Date(Date.now() - 180 * 86400000).toISOString().split('T')[0]!;
|
const startDate = new Date(Date.now() - 180 * 86400000).toISOString().split('T')[0]!;
|
||||||
|
|
||||||
const [statsData, revenueData] = await Promise.all([
|
const [statsData, revenueData] = await Promise.all([
|
||||||
adminApi.getDashboardStats(tokens.accessToken),
|
adminApi.getDashboardStats(),
|
||||||
adminApi.getRevenueStats(tokens.accessToken, startDate, endDate, 'month'),
|
adminApi.getRevenueStats(startDate, endDate, 'month'),
|
||||||
]);
|
]);
|
||||||
setStats(statsData);
|
setStats(statsData);
|
||||||
setRevenue(revenueData);
|
setRevenue(revenueData);
|
||||||
@@ -120,7 +117,7 @@ export default function AdminDashboardPage() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [tokens?.accessToken]);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchData();
|
fetchData();
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ import {
|
|||||||
DialogDescription,
|
DialogDescription,
|
||||||
DialogFooter,
|
DialogFooter,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
import {
|
import {
|
||||||
adminApi,
|
adminApi,
|
||||||
type UserListItem,
|
type UserListItem,
|
||||||
@@ -169,7 +168,6 @@ function UserDetailPanel({
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default function AdminUsersPage() {
|
export default function AdminUsersPage() {
|
||||||
const { tokens } = useAuthStore();
|
|
||||||
const [result, setResult] = useState<PaginatedResult<UserListItem> | null>(null);
|
const [result, setResult] = useState<PaginatedResult<UserListItem> | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -189,11 +187,10 @@ export default function AdminUsersPage() {
|
|||||||
const [actionError, setActionError] = useState<string | null>(null);
|
const [actionError, setActionError] = useState<string | null>(null);
|
||||||
|
|
||||||
const fetchUsers = useCallback(async () => {
|
const fetchUsers = useCallback(async () => {
|
||||||
if (!tokens?.accessToken) return;
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const data = await adminApi.getUsers(tokens.accessToken, {
|
const data = await adminApi.getUsers({
|
||||||
page,
|
page,
|
||||||
limit: 20,
|
limit: 20,
|
||||||
role: roleFilter || undefined,
|
role: roleFilter || undefined,
|
||||||
@@ -206,17 +203,16 @@ export default function AdminUsersPage() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [tokens?.accessToken, page, roleFilter, statusFilter, search]);
|
}, [page, roleFilter, statusFilter, search]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchUsers();
|
fetchUsers();
|
||||||
}, [fetchUsers]);
|
}, [fetchUsers]);
|
||||||
|
|
||||||
const openDetail = async (userId: string) => {
|
const openDetail = async (userId: string) => {
|
||||||
if (!tokens?.accessToken) return;
|
|
||||||
setDetailLoading(true);
|
setDetailLoading(true);
|
||||||
try {
|
try {
|
||||||
const detail = await adminApi.getUserDetail(tokens.accessToken, userId);
|
const detail = await adminApi.getUserDetail(userId);
|
||||||
setSelectedUser(detail);
|
setSelectedUser(detail);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setActionError(e instanceof Error ? e.message : 'Không thể tải chi tiết người dùng');
|
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 () => {
|
const confirmToggleStatus = async () => {
|
||||||
if (!tokens?.accessToken || !banDialog) return;
|
if (!banDialog) return;
|
||||||
setActionLoading(true);
|
setActionLoading(true);
|
||||||
try {
|
try {
|
||||||
await adminApi.banUser(
|
await adminApi.banUser(
|
||||||
tokens.accessToken,
|
|
||||||
banDialog.userId,
|
banDialog.userId,
|
||||||
banReason || 'Admin action',
|
banReason || 'Admin action',
|
||||||
banDialog.isActive, // unban = true if making active
|
banDialog.isActive, // unban = true if making active
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ export default function AdminLayout({ children }: { children: React.ReactNode })
|
|||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="w-full justify-start gap-2"
|
className="w-full justify-start gap-2"
|
||||||
onClick={logout}
|
onClick={() => logout()}
|
||||||
>
|
>
|
||||||
<LogOut className="h-4 w-4" />
|
<LogOut className="h-4 w-4" />
|
||||||
Đăng xuất
|
Đăng xuất
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
|||||||
{user.fullName}
|
{user.fullName}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
<Button variant="ghost" size="sm" onClick={logout}>
|
<Button variant="ghost" size="sm" onClick={() => logout()}>
|
||||||
Đăng xuất
|
Đăng xuất
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ import {
|
|||||||
type CreateListingFormData,
|
type CreateListingFormData,
|
||||||
} from '@/lib/validations/listings';
|
} from '@/lib/validations/listings';
|
||||||
import { listingsApi, type CreateListingPayload, type Direction } from '@/lib/listings-api';
|
import { listingsApi, type CreateListingPayload, type Direction } from '@/lib/listings-api';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
const STEPS = [
|
const STEPS = [
|
||||||
@@ -41,7 +40,6 @@ function toNum(val: string | undefined): number | undefined {
|
|||||||
|
|
||||||
export default function CreateListingPage() {
|
export default function CreateListingPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { tokens } = useAuthStore();
|
|
||||||
const [currentStep, setCurrentStep] = React.useState(0);
|
const [currentStep, setCurrentStep] = React.useState(0);
|
||||||
const [images, setImages] = React.useState<ImageFile[]>([]);
|
const [images, setImages] = React.useState<ImageFile[]>([]);
|
||||||
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||||
@@ -69,11 +67,6 @@ export default function CreateListingPage() {
|
|||||||
const goBack = () => setCurrentStep((s) => Math.max(s - 1, 0));
|
const goBack = () => setCurrentStep((s) => Math.max(s - 1, 0));
|
||||||
|
|
||||||
const onSubmit = async (data: CreateListingFormData) => {
|
const onSubmit = async (data: CreateListingFormData) => {
|
||||||
if (!tokens?.accessToken) {
|
|
||||||
setError('Vui lòng đăng nhập để đăng tin');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
@@ -117,11 +110,11 @@ export default function CreateListingPage() {
|
|||||||
const commissionPct = toNum(data.commissionPct);
|
const commissionPct = toNum(data.commissionPct);
|
||||||
if (commissionPct != null) payload.commissionPct = 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) {
|
for (const img of images) {
|
||||||
try {
|
try {
|
||||||
await listingsApi.uploadMedia(tokens.accessToken, result.listingId, img.file);
|
await listingsApi.uploadMedia(result.listingId, img.file);
|
||||||
} catch {
|
} catch {
|
||||||
// Continue with remaining images
|
// Continue with remaining images
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ import {
|
|||||||
type PaginatedResult,
|
type PaginatedResult,
|
||||||
} from '@/lib/listings-api';
|
} from '@/lib/listings-api';
|
||||||
import { PROPERTY_TYPES, TRANSACTION_TYPES, LISTING_STATUSES } from '@/lib/validations/listings';
|
import { PROPERTY_TYPES, TRANSACTION_TYPES, LISTING_STATUSES } from '@/lib/validations/listings';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
|
||||||
|
|
||||||
function formatPrice(priceVND: string): string {
|
function formatPrice(priceVND: string): string {
|
||||||
const num = Number(priceVND);
|
const num = Number(priceVND);
|
||||||
if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} ty`;
|
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';
|
type ViewMode = 'grid' | 'table';
|
||||||
|
|
||||||
export default function ListingsPage() {
|
export default function ListingsPage() {
|
||||||
const { tokens } = useAuthStore();
|
|
||||||
const [result, setResult] = React.useState<PaginatedResult<ListingDetail> | null>(null);
|
const [result, setResult] = React.useState<PaginatedResult<ListingDetail> | null>(null);
|
||||||
const [loading, setLoading] = React.useState(true);
|
const [loading, setLoading] = React.useState(true);
|
||||||
const [viewMode, setViewMode] = React.useState<ViewMode>('grid');
|
const [viewMode, setViewMode] = React.useState<ViewMode>('grid');
|
||||||
|
|||||||
@@ -30,11 +30,11 @@ export default function GoogleCallbackPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
handleOAuthCallback({
|
handleOAuthCallback(
|
||||||
accessToken,
|
accessToken,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
expiresIn: expiresIn ? Number(expiresIn) : 900,
|
expiresIn ? Number(expiresIn) : 900,
|
||||||
})
|
)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
const redirect = searchParams.get('redirect') || '/dashboard';
|
const redirect = searchParams.get('redirect') || '/dashboard';
|
||||||
router.replace(redirect);
|
router.replace(redirect);
|
||||||
|
|||||||
@@ -30,11 +30,11 @@ export default function ZaloCallbackPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
handleOAuthCallback({
|
handleOAuthCallback(
|
||||||
accessToken,
|
accessToken,
|
||||||
refreshToken,
|
refreshToken,
|
||||||
expiresIn: expiresIn ? Number(expiresIn) : 900,
|
expiresIn ? Number(expiresIn) : 900,
|
||||||
})
|
)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
const redirect = searchParams.get('redirect') || '/dashboard';
|
const redirect = searchParams.get('redirect') || '/dashboard';
|
||||||
router.replace(redirect);
|
router.replace(redirect);
|
||||||
|
|||||||
@@ -3,25 +3,12 @@
|
|||||||
import { useEffect } from 'react';
|
import { useEffect } from 'react';
|
||||||
import { useAuthStore } from '@/lib/auth-store';
|
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 }) {
|
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||||
const initialize = useAuthStore((s) => s.initialize);
|
const initialize = useAuthStore((s) => s.initialize);
|
||||||
const tokens = useAuthStore((s) => s.tokens);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
initialize();
|
initialize();
|
||||||
}, [initialize]);
|
}, [initialize]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setAuthCookie(!!tokens);
|
|
||||||
}, [tokens]);
|
|
||||||
|
|
||||||
return <>{children}</>;
|
return <>{children}</>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -96,87 +96,83 @@ export interface KycQueueItem {
|
|||||||
|
|
||||||
export const adminApi = {
|
export const adminApi = {
|
||||||
// Dashboard
|
// Dashboard
|
||||||
getDashboardStats: (token: string) =>
|
getDashboardStats: () =>
|
||||||
apiClient.authGet<DashboardStats>('/admin/dashboard', token),
|
apiClient.get<DashboardStats>('/admin/dashboard'),
|
||||||
|
|
||||||
getRevenueStats: (token: string, startDate: string, endDate: string, groupBy: 'day' | 'month' = 'month') =>
|
getRevenueStats: (startDate: string, endDate: string, groupBy: 'day' | 'month' = 'month') =>
|
||||||
apiClient.authGet<RevenueStatsItem[]>(
|
apiClient.get<RevenueStatsItem[]>(
|
||||||
`/admin/revenue?startDate=${startDate}&endDate=${endDate}&groupBy=${groupBy}`,
|
`/admin/revenue?startDate=${startDate}&endDate=${endDate}&groupBy=${groupBy}`,
|
||||||
token,
|
|
||||||
),
|
),
|
||||||
|
|
||||||
// Moderation
|
// Moderation
|
||||||
getModerationQueue: (token: string, page = 1, limit = 20) =>
|
getModerationQueue: (page = 1, limit = 20) =>
|
||||||
apiClient.authGet<PaginatedResult<ModerationQueueItem>>(
|
apiClient.get<PaginatedResult<ModerationQueueItem>>(
|
||||||
`/admin/moderation?page=${page}&limit=${limit}`,
|
`/admin/moderation?page=${page}&limit=${limit}`,
|
||||||
token,
|
|
||||||
),
|
),
|
||||||
|
|
||||||
approveListing: (token: string, listingId: string, moderationNotes?: string) =>
|
approveListing: (listingId: string, moderationNotes?: string) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/moderation/approve', token, {
|
apiClient.post<{ success: boolean }>('/admin/moderation/approve', {
|
||||||
listingId,
|
listingId,
|
||||||
moderationNotes,
|
moderationNotes,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
rejectListing: (token: string, listingId: string, reason: string) =>
|
rejectListing: (listingId: string, reason: string) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/moderation/reject', token, {
|
apiClient.post<{ success: boolean }>('/admin/moderation/reject', {
|
||||||
listingId,
|
listingId,
|
||||||
reason,
|
reason,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
bulkModerate: (token: string, listingIds: string[], action: 'approve' | 'reject', reason?: string) =>
|
bulkModerate: (listingIds: string[], action: 'approve' | 'reject', reason?: string) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/moderation/bulk', token, {
|
apiClient.post<{ success: boolean }>('/admin/moderation/bulk', {
|
||||||
listingIds,
|
listingIds,
|
||||||
action,
|
action,
|
||||||
reason,
|
reason,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// Users
|
// 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();
|
const query = new URLSearchParams();
|
||||||
if (params.page) query.set('page', String(params.page));
|
if (params.page) query.set('page', String(params.page));
|
||||||
if (params.limit) query.set('limit', String(params.limit));
|
if (params.limit) query.set('limit', String(params.limit));
|
||||||
if (params.role) query.set('role', params.role);
|
if (params.role) query.set('role', params.role);
|
||||||
if (params.isActive !== undefined) query.set('isActive', String(params.isActive));
|
if (params.isActive !== undefined) query.set('isActive', String(params.isActive));
|
||||||
if (params.search) query.set('search', params.search);
|
if (params.search) query.set('search', params.search);
|
||||||
return apiClient.authGet<PaginatedResult<UserListItem>>(
|
return apiClient.get<PaginatedResult<UserListItem>>(
|
||||||
`/admin/users?${query.toString()}`,
|
`/admin/users?${query.toString()}`,
|
||||||
token,
|
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
getUserDetail: (token: string, userId: string) =>
|
getUserDetail: (userId: string) =>
|
||||||
apiClient.authGet<UserDetail>(`/admin/users/${userId}`, token),
|
apiClient.get<UserDetail>(`/admin/users/${userId}`),
|
||||||
|
|
||||||
updateUserStatus: (token: string, userId: string, isActive: boolean, reason?: string) =>
|
updateUserStatus: (userId: string, isActive: boolean, reason?: string) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/users/status', token, {
|
apiClient.post<{ success: boolean }>('/admin/users/status', {
|
||||||
userId,
|
userId,
|
||||||
isActive,
|
isActive,
|
||||||
reason,
|
reason,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
banUser: (token: string, userId: string, reason: string, unban = false) =>
|
banUser: (userId: string, reason: string, unban = false) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/users/ban', token, {
|
apiClient.post<{ success: boolean }>('/admin/users/ban', {
|
||||||
userId,
|
userId,
|
||||||
reason,
|
reason,
|
||||||
unban,
|
unban,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
// KYC
|
// KYC
|
||||||
getKycQueue: (token: string, page = 1, limit = 20) =>
|
getKycQueue: (page = 1, limit = 20) =>
|
||||||
apiClient.authGet<PaginatedResult<KycQueueItem>>(
|
apiClient.get<PaginatedResult<KycQueueItem>>(
|
||||||
`/admin/kyc?page=${page}&limit=${limit}`,
|
`/admin/kyc?page=${page}&limit=${limit}`,
|
||||||
token,
|
|
||||||
),
|
),
|
||||||
|
|
||||||
approveKyc: (token: string, userId: string, notes?: string) =>
|
approveKyc: (userId: string, notes?: string) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/kyc/approve', token, {
|
apiClient.post<{ success: boolean }>('/admin/kyc/approve', {
|
||||||
userId,
|
userId,
|
||||||
notes,
|
notes,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
rejectKyc: (token: string, userId: string, reason: string) =>
|
rejectKyc: (userId: string, reason: string) =>
|
||||||
apiClient.authPost<{ success: boolean }>('/admin/kyc/reject', token, {
|
apiClient.post<{ success: boolean }>('/admin/kyc/reject', {
|
||||||
userId,
|
userId,
|
||||||
reason,
|
reason,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ type RequestOptions = Omit<RequestInit, 'body'> & {
|
|||||||
function getCsrfToken(): string | undefined {
|
function getCsrfToken(): string | undefined {
|
||||||
if (typeof document === 'undefined') return undefined;
|
if (typeof document === 'undefined') return undefined;
|
||||||
const match = document.cookie.match(/(?:^|;\s*)XSRF-TOKEN=([^;]*)/);
|
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']);
|
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||||
@@ -53,10 +53,6 @@ async function request<T>(endpoint: string, options: RequestOptions = {}): Promi
|
|||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
function authHeaders(token: string): HeadersInit {
|
|
||||||
return { Authorization: `Bearer ${token}` };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const apiClient = {
|
export const apiClient = {
|
||||||
get: <T>(endpoint: string, headers?: HeadersInit) =>
|
get: <T>(endpoint: string, headers?: HeadersInit) =>
|
||||||
request<T>(endpoint, { method: 'GET', headers }),
|
request<T>(endpoint, { method: 'GET', headers }),
|
||||||
@@ -67,12 +63,6 @@ export const apiClient = {
|
|||||||
patch: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
|
patch: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
|
||||||
request<T>(endpoint, { method: 'PATCH', body, headers }),
|
request<T>(endpoint, { method: 'PATCH', body, headers }),
|
||||||
|
|
||||||
authGet: <T>(endpoint: string, token: string) =>
|
delete: <T>(endpoint: string, headers?: HeadersInit) =>
|
||||||
request<T>(endpoint, { method: 'GET', headers: authHeaders(token) }),
|
request<T>(endpoint, { method: 'DELETE', headers }),
|
||||||
|
|
||||||
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) }),
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
import { apiClient } from './api-client';
|
import { apiClient } from './api-client';
|
||||||
|
|
||||||
export interface TokenPair {
|
|
||||||
accessToken: string;
|
|
||||||
refreshToken: string;
|
|
||||||
expiresIn: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UserProfile {
|
export interface UserProfile {
|
||||||
id: string;
|
id: string;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
@@ -31,12 +25,24 @@ export interface LoginPayload {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const authApi = {
|
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) =>
|
refresh: () =>
|
||||||
apiClient.post<TokenPair>('/auth/refresh', { refreshToken }),
|
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 { 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';
|
import { ApiError } from './api-client';
|
||||||
|
|
||||||
export type { TokenPair };
|
function hasAuthCookie(): boolean {
|
||||||
|
if (typeof document === 'undefined') return false;
|
||||||
const TOKEN_KEY = 'goodgo_tokens';
|
return document.cookie.includes('goodgo_authenticated=1');
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AuthState {
|
interface AuthState {
|
||||||
tokens: TokenPair | null;
|
|
||||||
user: UserProfile | null;
|
user: UserProfile | null;
|
||||||
|
isAuthenticated: boolean;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
error: string | null;
|
error: string | null;
|
||||||
|
|
||||||
login: (data: LoginPayload) => Promise<void>;
|
login: (data: LoginPayload) => Promise<void>;
|
||||||
register: (data: RegisterPayload) => Promise<void>;
|
register: (data: RegisterPayload) => Promise<void>;
|
||||||
handleOAuthCallback: (tokens: TokenPair) => Promise<void>;
|
handleOAuthCallback: (accessToken: string, refreshToken: string, expiresIn?: number) => Promise<void>;
|
||||||
logout: () => void;
|
logout: () => Promise<void>;
|
||||||
refreshToken: () => Promise<boolean>;
|
refreshToken: () => Promise<boolean>;
|
||||||
fetchProfile: () => Promise<void>;
|
fetchProfile: () => Promise<void>;
|
||||||
initialize: () => Promise<void>;
|
initialize: () => Promise<void>;
|
||||||
@@ -43,17 +24,16 @@ interface AuthState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const useAuthStore = create<AuthState>((set, get) => ({
|
export const useAuthStore = create<AuthState>((set, get) => ({
|
||||||
tokens: null,
|
|
||||||
user: null,
|
user: null,
|
||||||
|
isAuthenticated: false,
|
||||||
isLoading: false,
|
isLoading: false,
|
||||||
error: null,
|
error: null,
|
||||||
|
|
||||||
login: async (data) => {
|
login: async (data) => {
|
||||||
set({ isLoading: true, error: null });
|
set({ isLoading: true, error: null });
|
||||||
try {
|
try {
|
||||||
const tokens = await authApi.login(data);
|
await authApi.login(data);
|
||||||
persistTokens(tokens);
|
set({ isAuthenticated: true, isLoading: false });
|
||||||
set({ tokens, isLoading: false });
|
|
||||||
await get().fetchProfile();
|
await get().fetchProfile();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const message = e instanceof ApiError ? e.message : 'Đăng nhập thất bại';
|
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) => {
|
register: async (data) => {
|
||||||
set({ isLoading: true, error: null });
|
set({ isLoading: true, error: null });
|
||||||
try {
|
try {
|
||||||
const tokens = await authApi.register(data);
|
await authApi.register(data);
|
||||||
persistTokens(tokens);
|
set({ isAuthenticated: true, isLoading: false });
|
||||||
set({ tokens, isLoading: false });
|
|
||||||
await get().fetchProfile();
|
await get().fetchProfile();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const message = e instanceof ApiError ? e.message : 'Đăng ký thất bại';
|
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 });
|
set({ isLoading: true, error: null });
|
||||||
try {
|
try {
|
||||||
persistTokens(tokens);
|
await authApi.exchangeToken(accessToken, refreshToken, expiresIn);
|
||||||
set({ tokens, isLoading: false });
|
set({ isAuthenticated: true, isLoading: false });
|
||||||
await get().fetchProfile();
|
await get().fetchProfile();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const message = e instanceof ApiError ? e.message : 'Đăng nhập OAuth thất bại';
|
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: () => {
|
logout: async () => {
|
||||||
persistTokens(null);
|
try {
|
||||||
set({ tokens: null, user: null, error: null });
|
await authApi.logout();
|
||||||
|
} catch {
|
||||||
|
// Clear state even if API call fails
|
||||||
|
}
|
||||||
|
set({ user: null, isAuthenticated: false, error: null });
|
||||||
},
|
},
|
||||||
|
|
||||||
refreshToken: async () => {
|
refreshToken: async () => {
|
||||||
const { tokens } = get();
|
|
||||||
if (!tokens?.refreshToken) return false;
|
|
||||||
try {
|
try {
|
||||||
const newTokens = await authApi.refresh(tokens.refreshToken);
|
await authApi.refresh();
|
||||||
persistTokens(newTokens);
|
set({ isAuthenticated: true });
|
||||||
set({ tokens: newTokens });
|
|
||||||
return true;
|
return true;
|
||||||
} catch {
|
} catch {
|
||||||
get().logout();
|
set({ user: null, isAuthenticated: false });
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
fetchProfile: async () => {
|
fetchProfile: async () => {
|
||||||
const { tokens } = get();
|
|
||||||
if (!tokens?.accessToken) return;
|
|
||||||
try {
|
try {
|
||||||
const user = await authApi.getProfile(tokens.accessToken);
|
const user = await authApi.getProfile();
|
||||||
set({ user });
|
set({ user, isAuthenticated: true });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof ApiError && e.status === 401) {
|
if (e instanceof ApiError && e.status === 401) {
|
||||||
const refreshed = await get().refreshToken();
|
const refreshed = await get().refreshToken();
|
||||||
if (refreshed) {
|
if (refreshed) {
|
||||||
const newTokens = get().tokens;
|
try {
|
||||||
if (newTokens) {
|
const user = await authApi.getProfile();
|
||||||
const user = await authApi.getProfile(newTokens.accessToken);
|
set({ user, isAuthenticated: true });
|
||||||
set({ user });
|
} catch {
|
||||||
|
set({ user: null, isAuthenticated: false });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,9 +108,8 @@ export const useAuthStore = create<AuthState>((set, get) => ({
|
|||||||
},
|
},
|
||||||
|
|
||||||
initialize: async () => {
|
initialize: async () => {
|
||||||
const tokens = loadTokens();
|
if (!hasAuthCookie()) return;
|
||||||
if (!tokens) return;
|
set({ isAuthenticated: true });
|
||||||
set({ tokens });
|
|
||||||
await get().fetchProfile();
|
await get().fetchProfile();
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -134,10 +134,9 @@ export interface SearchListingsParams {
|
|||||||
const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001';
|
const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001';
|
||||||
|
|
||||||
export const listingsApi = {
|
export const listingsApi = {
|
||||||
create: (token: string, data: CreateListingPayload) =>
|
create: (data: CreateListingPayload) =>
|
||||||
apiClient.authPost<{ listingId: string; propertyId: string; status: string }>(
|
apiClient.post<{ listingId: string; propertyId: string; status: string }>(
|
||||||
'/listings',
|
'/listings',
|
||||||
token,
|
|
||||||
data,
|
data,
|
||||||
),
|
),
|
||||||
|
|
||||||
@@ -152,20 +151,20 @@ export const listingsApi = {
|
|||||||
return apiClient.get<PaginatedResult<ListingDetail>>(`/listings${qs ? `?${qs}` : ''}`);
|
return apiClient.get<PaginatedResult<ListingDetail>>(`/listings${qs ? `?${qs}` : ''}`);
|
||||||
},
|
},
|
||||||
|
|
||||||
updateStatus: (token: string, id: string, status: ListingStatus, moderationNotes?: string) =>
|
updateStatus: (id: string, status: ListingStatus, moderationNotes?: string) =>
|
||||||
apiClient.authPost<{ status: string }>(`/listings/${id}/status`, token, {
|
apiClient.post<{ status: string }>(`/listings/${id}/status`, {
|
||||||
status,
|
status,
|
||||||
moderationNotes,
|
moderationNotes,
|
||||||
}),
|
}),
|
||||||
|
|
||||||
uploadMedia: async (token: string, listingId: string, file: File, caption?: string) => {
|
uploadMedia: async (listingId: string, file: File, caption?: string) => {
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
if (caption) formData.append('caption', caption);
|
if (caption) formData.append('caption', caption);
|
||||||
|
|
||||||
const res = await fetch(`${API_BASE_URL}/listings/${listingId}/media`, {
|
const res = await fetch(`${API_BASE_URL}/listings/${listingId}/media`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { Authorization: `Bearer ${token}` },
|
credentials: 'include',
|
||||||
body: formData,
|
body: formData,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user