Compare commits
5 Commits
staging
...
2ee5c8da36
| Author | SHA1 | Date | |
|---|---|---|---|
| 2ee5c8da36 | |||
| 3dc7804b10 | |||
| fc3d900871 | |||
| 4018d8e135 | |||
| 1fe25c1944 |
@@ -1,73 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { PUBLIC_ROUTES, canAccessRoute, UserRole } from "./src/config/routes.config"
|
||||
|
||||
/**
|
||||
* Middleware để kiểm tra authentication và authorization
|
||||
* Chạy TRƯỚC khi render page
|
||||
*/
|
||||
export async function middleware(request: NextRequest) {
|
||||
const { pathname } = request.nextUrl
|
||||
|
||||
// 1. Kiểm tra nếu là public route
|
||||
if (PUBLIC_ROUTES.includes(pathname)) {
|
||||
// Nếu user đã login, không cho vào signin/signup
|
||||
const userDataCookie = request.cookies.get("userDataRedux")
|
||||
if (userDataCookie && (pathname === "/signin" || pathname === "/signup")) {
|
||||
return NextResponse.redirect(new URL("/", request.url))
|
||||
}
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
// 2. Kiểm tra user data cookie (prioritize này để tránh redirect loop)
|
||||
const userDataCookie = request.cookies.get("userDataRedux")
|
||||
|
||||
if (userDataCookie) {
|
||||
try {
|
||||
const userData = JSON.parse(userDataCookie.value)
|
||||
const userRoles: UserRole[] = userData.roles?.map((r: any) => r.name) || []
|
||||
|
||||
// Kiểm tra user có quyền truy cập route này không
|
||||
if (!canAccessRoute(userRoles, pathname)) {
|
||||
// Redirect về 403 page
|
||||
return NextResponse.redirect(new URL("/error-403", request.url))
|
||||
}
|
||||
|
||||
// User có quyền, cho qua
|
||||
return NextResponse.next()
|
||||
} catch (error) {
|
||||
console.error("Error parsing user data in middleware:", error)
|
||||
// Xóa cookie lỗi
|
||||
const response = NextResponse.redirect(new URL("/signin", request.url))
|
||||
response.cookies.delete("userDataRedux")
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Kiểm tra token từ backend (HTTP-only cookie)
|
||||
const token = request.cookies.get("token") || request.cookies.get("access_token")
|
||||
|
||||
// 4. Nếu không có token và không có user data, redirect về signin
|
||||
if (!token) {
|
||||
const signinUrl = new URL("/signin", request.url)
|
||||
signinUrl.searchParams.set("from", pathname)
|
||||
return NextResponse.redirect(signinUrl)
|
||||
}
|
||||
|
||||
return NextResponse.next()
|
||||
}
|
||||
|
||||
/**
|
||||
* Cấu hình matcher - middleware chỉ chạy cho những routes này
|
||||
*/
|
||||
export const config = {
|
||||
matcher: [
|
||||
/*
|
||||
* Chạy middleware cho tất cả paths ngoại trừ:
|
||||
* - _next/static (static files)
|
||||
* - _next/image (image optimization files)
|
||||
* - favicon.ico (favicon file)
|
||||
* - public folder
|
||||
*/
|
||||
"/((?!_next/static|_next/image|favicon.ico|public).*)",
|
||||
],
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import ComponentCard from "@/components/common/ComponentCard";
|
||||
import PageBreadcrumb from "@/components/common/PageBreadCrumb";
|
||||
import Pagination from "@/components/tables/Pagination";
|
||||
import Swal from "sweetalert2";
|
||||
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
|
||||
|
||||
import ApplicationTable, {
|
||||
AppSortColumn,
|
||||
@@ -191,9 +190,8 @@ export default function HistorianApplicationPage() {
|
||||
console.log(tableData)
|
||||
// console.log("Pagination info:", pagination);
|
||||
return (
|
||||
<ProtectedRoute requiredRoles={["ADMIN", "MOD", "HISTORIAN"]}>
|
||||
<div>
|
||||
<PageBreadcrumb pageTitle="Quản lý hồ sơ" />
|
||||
<div>
|
||||
<PageBreadcrumb pageTitle="Quản lý hồ sơ" />
|
||||
|
||||
<div className="space-y-6">
|
||||
<ComponentCard
|
||||
@@ -220,6 +218,7 @@ export default function HistorianApplicationPage() {
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{/* Cập nhật Grid để chứa đủ các ô filter */}
|
||||
<div className="grid grid-cols-1 gap-4 mb-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">Tìm kiếm</label>
|
||||
@@ -355,6 +354,5 @@ export default function HistorianApplicationPage() {
|
||||
onRefresh={fetchApplications}
|
||||
/>
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import Pagination from "@/components/tables/Pagination";
|
||||
import { LIMIT_ITEM_TABLE } from "../../../../../../constant";
|
||||
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
|
||||
|
||||
export type SortColumn = "created_at" | "updated_at" | "display_name" | "email";
|
||||
|
||||
@@ -33,9 +32,7 @@ const formatDateTimeToISO = (
|
||||
|
||||
export default function UserTable() {
|
||||
const [page, setPage] = useState<number>(1);
|
||||
const [limitInput, setLimitInput] = useState<string>(
|
||||
LIMIT_ITEM_TABLE.toString(),
|
||||
);
|
||||
const [limitInput, setLimitInput] = useState<string>(LIMIT_ITEM_TABLE.toString());
|
||||
|
||||
const [selectedRole, setSelectedRole] = useState<string>("");
|
||||
const [roles, setRoles] = useState<{ id: string; name: string }[]>([]);
|
||||
@@ -146,6 +143,7 @@ export default function UserTable() {
|
||||
role_ids: selectedRole ? [selectedRole] : undefined,
|
||||
};
|
||||
|
||||
// Thêm format ngày giờ vào payload
|
||||
const createdFrom = formatDateTimeToISO(
|
||||
debouncedParams.fromDate,
|
||||
debouncedParams.fromTime,
|
||||
@@ -187,7 +185,7 @@ export default function UserTable() {
|
||||
};
|
||||
|
||||
const pagination = tableData?.pagination;
|
||||
|
||||
|
||||
// console.log(pagination);
|
||||
|
||||
const handleOpenDetail = (user: fullDataUser) => {
|
||||
@@ -253,197 +251,192 @@ export default function UserTable() {
|
||||
};
|
||||
|
||||
return (
|
||||
<ProtectedRoute requiredRoles={["ADMIN", "MOD"]}>
|
||||
<div>
|
||||
<PageBreadcrumb pageTitle="Quản lý người dùng" />
|
||||
<div className="space-y-6">
|
||||
<ComponentCard
|
||||
title="Bộ lọc tìm kiếm"
|
||||
headerAction={
|
||||
<button
|
||||
onClick={handleReset}
|
||||
className="flex items-center px-3 py-1.5 text-xs text-red-500 transition-colors border-red-100 dark:bg-red-500/10 dark:border-red-500/20 dark:hover:bg-red-500/20"
|
||||
<div>
|
||||
<PageBreadcrumb pageTitle="Quản lý người dùng" />
|
||||
<div className="space-y-6">
|
||||
<ComponentCard
|
||||
title="Bộ lọc tìm kiếm"
|
||||
headerAction={
|
||||
<button
|
||||
onClick={handleReset}
|
||||
className="flex items-center px-3 py-1.5 text-xs text-red-500 transition-colors border-red-100 dark:bg-red-500/10 dark:border-red-500/20 dark:hover:bg-red-500/20"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="w-7 h-7"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="w-7 h-7"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2.5}
|
||||
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 mb-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">Search</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Name, email..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2.5}
|
||||
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Auth Provider
|
||||
</label>
|
||||
<select
|
||||
value={authProvider}
|
||||
onChange={(e) => setAuthProvider(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 cursor-pointer bg-white outline-none focus:border-brand-500"
|
||||
>
|
||||
<option value="">Tất cả</option>
|
||||
<option value="google">Google</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Trạng thái xóa
|
||||
</label>
|
||||
<select
|
||||
onChange={(e) =>
|
||||
setIsDeleted(
|
||||
e.target.value === ""
|
||||
? undefined
|
||||
: e.target.value === "true",
|
||||
)
|
||||
}
|
||||
value={
|
||||
isDeleted === undefined ? "" : isDeleted ? "true" : "false"
|
||||
}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500 cursor-pointer"
|
||||
>
|
||||
<option value="">Tất cả</option>
|
||||
<option value="false">Hoạt động</option>
|
||||
<option value="true">Đã xóa</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Từ ngày
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="date"
|
||||
value={fromDate}
|
||||
onChange={(e) => setFromDate(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
value={fromTime}
|
||||
onChange={(e) => setFromTime(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Đến ngày
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="date"
|
||||
value={toDate}
|
||||
onChange={(e) => setToDate(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
value={toTime}
|
||||
onChange={(e) => setToTime(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Số lượng (Limit)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={limitInput}
|
||||
onChange={(e) => setLimitInput(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ComponentCard>
|
||||
|
||||
<ComponentCard title="Danh sách người dùng">
|
||||
<div className="relative min-h-[300px]">
|
||||
{loading && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-white/50 dark:bg-gray-900/50 rounded-xl">
|
||||
<div className="w-10 h-10 border-4 border-t-brand-500 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<BasicTableOne
|
||||
data={tableData?.data || []}
|
||||
onSort={handleSort}
|
||||
sortBy={sortBy}
|
||||
sortOrder={sortOrder}
|
||||
onViewDetail={handleOpenDetail}
|
||||
roles={roles}
|
||||
selectedRole={selectedRole}
|
||||
onFilterRole={(role) => setSelectedRole(role)}
|
||||
</svg>
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<div className="grid grid-cols-1 gap-4 mb-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">Search</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Name, email..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between mt-6">
|
||||
<p className="text-sm text-gray-500">
|
||||
Hiển thị trang {pagination?.current_page || 1} /{" "}
|
||||
{pagination?.total_pages || 1} ({pagination?.total_records || 0}{" "}
|
||||
kết quả)
|
||||
</p>
|
||||
|
||||
{pagination && pagination.total_pages > 1 && (
|
||||
<Pagination
|
||||
currentPage={pagination.current_page}
|
||||
totalPages={pagination.total_pages}
|
||||
onPageChange={(newPage) => setPage(newPage)}
|
||||
/>
|
||||
)}
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Auth Provider
|
||||
</label>
|
||||
<select
|
||||
value={authProvider}
|
||||
onChange={(e) => setAuthProvider(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 cursor-pointer bg-white outline-none focus:border-brand-500"
|
||||
>
|
||||
<option value="">Tất cả</option>
|
||||
<option value="google">Google</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<UserDetailModal
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
user={selectedUser}
|
||||
onChangeRole={handleOpenRoleModal}
|
||||
onDelete={(u) => {
|
||||
handleDelete(u);
|
||||
setIsModalOpen(false);
|
||||
}}
|
||||
onRestore={(u) => {
|
||||
handleRestore(u);
|
||||
setIsModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Trạng thái xóa
|
||||
</label>
|
||||
<select
|
||||
onChange={(e) =>
|
||||
setIsDeleted(
|
||||
e.target.value === ""
|
||||
? undefined
|
||||
: e.target.value === "true",
|
||||
)
|
||||
}
|
||||
value={isDeleted === undefined ? "" : isDeleted ? "true" : "false"}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500 cursor-pointer"
|
||||
>
|
||||
<option value="">Tất cả</option>
|
||||
<option value="false">Hoạt động</option>
|
||||
<option value="true">Đã xóa</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<ChangeRoleModal
|
||||
isOpen={isRoleModalOpen}
|
||||
onClose={() => setIsRoleModalOpen(false)}
|
||||
user={roleUser}
|
||||
onSuccess={fetchUsers}
|
||||
{/* Từ ngày */}
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">Từ ngày</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="date"
|
||||
value={fromDate}
|
||||
onChange={(e) => setFromDate(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
value={fromTime}
|
||||
onChange={(e) => setFromTime(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Đến ngày */}
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">Đến ngày</label>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="date"
|
||||
value={toDate}
|
||||
onChange={(e) => setToDate(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
<input
|
||||
type="time"
|
||||
value={toTime}
|
||||
onChange={(e) => setToTime(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Limit */}
|
||||
<div>
|
||||
<label className="block mb-2 text-sm font-medium">
|
||||
Số lượng (Limit)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={limitInput}
|
||||
onChange={(e) => setLimitInput(e.target.value)}
|
||||
className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 outline-none focus:border-brand-500"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</ComponentCard>
|
||||
|
||||
<ComponentCard title="Danh sách người dùng">
|
||||
<div className="relative min-h-[300px]">
|
||||
{loading && (
|
||||
<div className="absolute inset-0 z-10 flex items-center justify-center bg-white/50 dark:bg-gray-900/50 rounded-xl">
|
||||
<div className="w-10 h-10 border-4 border-t-brand-500 rounded-full animate-spin"></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<BasicTableOne
|
||||
data={tableData?.data || []}
|
||||
onSort={handleSort}
|
||||
sortBy={sortBy}
|
||||
sortOrder={sortOrder}
|
||||
onViewDetail={handleOpenDetail}
|
||||
roles={roles}
|
||||
selectedRole={selectedRole}
|
||||
onFilterRole={(role) => setSelectedRole(role)}
|
||||
/>
|
||||
</ComponentCard>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between mt-6">
|
||||
<p className="text-sm text-gray-500">
|
||||
Hiển thị trang {pagination?.current_page || 1} /{" "}
|
||||
{pagination?.total_pages || 1} ({pagination?.total_records || 0}{" "}
|
||||
kết quả)
|
||||
</p>
|
||||
|
||||
{pagination && pagination.total_pages > 1 && (
|
||||
<Pagination
|
||||
currentPage={pagination.current_page}
|
||||
totalPages={pagination.total_pages}
|
||||
onPageChange={(newPage) => setPage(newPage)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<UserDetailModal
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
user={selectedUser}
|
||||
onChangeRole={handleOpenRoleModal}
|
||||
onDelete={(u) => {
|
||||
handleDelete(u);
|
||||
setIsModalOpen(false);
|
||||
}}
|
||||
onRestore={(u) => {
|
||||
handleRestore(u);
|
||||
setIsModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ChangeRoleModal
|
||||
isOpen={isRoleModalOpen}
|
||||
onClose={() => setIsRoleModalOpen(false)}
|
||||
user={roleUser}
|
||||
onSuccess={fetchUsers}
|
||||
/>
|
||||
</ComponentCard>
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -38,18 +38,6 @@ export default function ApplicationDetailPage() {
|
||||
|
||||
const config = statusConfig[application.status] || statusConfig.PENDING;
|
||||
|
||||
const formatDate = (dateString: string | null | undefined) => {
|
||||
if (!dateString) return "-";
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString("vi-VN", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
const isImageFile = (file: any) => {
|
||||
const isImageMime = file.mime_type?.startsWith("image/");
|
||||
const isImageExt = /\.(jpg|jpeg|png|webp|gif)$/i.test(file.storage_key);
|
||||
@@ -130,6 +118,17 @@ export default function ApplicationDetailPage() {
|
||||
}
|
||||
}
|
||||
};
|
||||
const formatDate = (dateString: string | null | undefined) => {
|
||||
if (!dateString) return "-";
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString("vi-VN", {
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
};
|
||||
|
||||
// console.log("Application Detail:", application);
|
||||
|
||||
@@ -226,57 +225,55 @@ export default function ApplicationDetailPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{application?.reviewer && (
|
||||
<section className="pt-8 border-t border-zinc-200 dark:border-zinc-800">
|
||||
<label className="text-[11px] font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider mb-3 block">
|
||||
Phản hồi từ người kiểm duyệt
|
||||
</label>
|
||||
{application?.reviewer && (
|
||||
<section className="pt-8 border-t border-zinc-200 dark:border-zinc-800">
|
||||
<label className="text-[11px] font-bold text-zinc-500 dark:text-zinc-400 uppercase tracking-wider mb-3 block">
|
||||
Phản hồi từ người kiểm duyệt
|
||||
</label>
|
||||
|
||||
<div className="p-5 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50">
|
||||
<div className="flex items-start justify-between mb-5">
|
||||
<div className="flex items-center gap-3">
|
||||
{application?.reviewer?.avatar_url ? (
|
||||
<Image
|
||||
src={application.reviewer.avatar_url}
|
||||
alt={application.reviewer.display_name || "Avatar"}
|
||||
width={36}
|
||||
height={36}
|
||||
className="w-9 h-9 rounded-full object-cover border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-800"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-9 h-9 rounded-full bg-zinc-200 dark:bg-zinc-800 flex items-center justify-center text-zinc-500 font-medium text-sm">
|
||||
{application?.reviewer?.display_name?.charAt(0) || "R"}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{application?.reviewer?.display_name}
|
||||
</h4>
|
||||
<p className="text-[11px] text-zinc-500 dark:text-zinc-400">
|
||||
{application?.reviewer?.email}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-[11px] text-zinc-400 dark:text-zinc-500 tabular-nums">
|
||||
{formatDate(application?.reviewed_at)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="relative ml-4 pl-4 border-l border-zinc-300 dark:border-zinc-700">
|
||||
<div className="text-sm text-zinc-700 dark:text-zinc-300 leading-relaxed">
|
||||
{application?.review_note ? (
|
||||
<p>{application.review_note}</p>
|
||||
) : (
|
||||
<p className="italic text-zinc-500">
|
||||
Không có ghi chú bổ sung.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-5 rounded-xl border border-zinc-200 dark:border-zinc-800 bg-zinc-50/50 dark:bg-zinc-900/50">
|
||||
<div className="flex items-start justify-between mb-5">
|
||||
<div className="flex items-center gap-3">
|
||||
{application?.reviewer?.avatar_url ? (
|
||||
<Image
|
||||
src={application.reviewer.avatar_url}
|
||||
alt={application.reviewer.display_name || "Avatar"}
|
||||
width={36}
|
||||
height={36}
|
||||
className="w-9 h-9 rounded-full object-cover border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-800"
|
||||
/>
|
||||
) : (
|
||||
<div className="w-9 h-9 rounded-full bg-zinc-200 dark:bg-zinc-800 flex items-center justify-center text-zinc-500 font-medium text-sm">
|
||||
{application?.reviewer?.display_name?.charAt(0) || "R"}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
)}
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
|
||||
{application?.reviewer?.display_name}
|
||||
</h4>
|
||||
<p className="text-[11px] text-zinc-500 dark:text-zinc-400">
|
||||
{application?.reviewer?.email}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className="text-[11px] text-zinc-400 dark:text-zinc-500 tabular-nums">
|
||||
{formatDate(application?.reviewed_at)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="relative ml-4 pl-4 border-l border-zinc-300 dark:border-zinc-700">
|
||||
<div className="text-sm text-zinc-700 dark:text-zinc-300 leading-relaxed">
|
||||
{application?.review_note ? (
|
||||
<p>{application.review_note}</p>
|
||||
) : (
|
||||
<p className="italic text-zinc-500">Không có ghi chú bổ sung.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Lightbox
|
||||
|
||||
@@ -9,14 +9,17 @@ import { MediaDto } from "@/interface/media";
|
||||
import { UserMetaCardProps } from "@/interface/user";
|
||||
import { apiGetCurrentUser } from "@/service/auth";
|
||||
import { apiGetCurrentUserApplications, apiGetCurrentUserMedia } from "@/service/userService";
|
||||
import { setUserData } from "@/store/features/userSlice";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
|
||||
export default function Profile() {
|
||||
const [user, setUser] = useState<UserMetaCardProps | null>(null);
|
||||
const [mediaData, setMediaData] = useState<MediaDto | null>(null);
|
||||
const [applications, setApplications] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const dispatch = useDispatch();
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
@@ -24,11 +27,12 @@ export default function Profile() {
|
||||
const mediaResponse = await apiGetCurrentUserMedia();
|
||||
const userApplications = await apiGetCurrentUserApplications();
|
||||
|
||||
console.log(userData);
|
||||
console.log("user", userData);
|
||||
|
||||
if (userApplications?.data) {
|
||||
setApplications(userApplications.data);
|
||||
}
|
||||
dispatch(setUserData(userData.data));
|
||||
|
||||
setMediaData(mediaResponse);
|
||||
setUser(userData);
|
||||
|
||||
@@ -4,7 +4,10 @@ import { useSidebar } from "@/context/SidebarContext";
|
||||
import AppHeader from "@/layout/AppHeader";
|
||||
import AppSidebar from "@/layout/AppSidebar";
|
||||
import Backdrop from "@/layout/Backdrop";
|
||||
import React from "react";
|
||||
import { apiGetCurrentUser } from "@/service/auth";
|
||||
import { setUserData } from "@/store/features/userSlice";
|
||||
import React, { useEffect } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
|
||||
export default function AdminLayout({
|
||||
children,
|
||||
@@ -12,13 +15,27 @@ export default function AdminLayout({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { isExpanded, isHovered, isMobileOpen } = useSidebar();
|
||||
const dispatch = useDispatch()
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
const userData = await apiGetCurrentUser();
|
||||
dispatch(setUserData(userData.data));
|
||||
} catch (err) {
|
||||
console.error("Lỗi:", err);
|
||||
}
|
||||
};
|
||||
fetchUser();
|
||||
}, [])
|
||||
|
||||
|
||||
// Dynamic class for main content margin based on sidebar state
|
||||
const mainContentMargin = isMobileOpen
|
||||
? "ml-0"
|
||||
: isExpanded || isHovered
|
||||
? "lg:ml-[290px]"
|
||||
: "lg:ml-[90px]";
|
||||
? "lg:ml-[290px]"
|
||||
: "lg:ml-[90px]";
|
||||
|
||||
return (
|
||||
<div className="min-h-screen xl:flex">
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import GridShape from "@/components/common/GridShape";
|
||||
import { Metadata } from "next";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
import React from "react";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Access Denied - 403 | Admin Dashboard",
|
||||
description:
|
||||
"This is Access Denied 403 page - you do not have permission to access this resource",
|
||||
};
|
||||
|
||||
export default function Error403() {
|
||||
return (
|
||||
<div className="relative flex flex-col items-center justify-center min-h-screen p-6 overflow-hidden z-1">
|
||||
<GridShape />
|
||||
<div className="mx-auto w-full max-w-[242px] text-center sm:max-w-[472px]">
|
||||
<h1 className="mb-8 font-bold text-gray-800 text-title-md dark:text-white/90 xl:text-title-2xl">
|
||||
403 - ACCESS DENIED
|
||||
</h1>
|
||||
|
||||
<Image
|
||||
src="/images/error/404.svg"
|
||||
alt="403"
|
||||
className="dark:hidden"
|
||||
width={472}
|
||||
height={152}
|
||||
/>
|
||||
<Image
|
||||
src="/images/error/404-dark.svg"
|
||||
alt="403"
|
||||
className="hidden dark:block"
|
||||
width={472}
|
||||
height={152}
|
||||
/>
|
||||
|
||||
<p className="mt-10 mb-6 text-base text-gray-700 dark:text-gray-400 sm:text-lg">
|
||||
You do not have permission to access this resource. Please contact your administrator if you believe this is a mistake.
|
||||
</p>
|
||||
|
||||
<Link
|
||||
href="/"
|
||||
className="inline-flex items-center justify-center rounded-lg border border-gray-300 bg-white px-5 py-3.5 text-sm font-medium text-gray-700 shadow-theme-xs hover:bg-gray-50 hover:text-gray-800 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:hover:bg-white/[0.03] dark:hover:text-gray-200"
|
||||
>
|
||||
Back to Home Page
|
||||
</Link>
|
||||
</div>
|
||||
<p className="absolute text-sm text-center text-gray-500 -translate-x-1/2 bottom-6 left-1/2 dark:text-gray-400">
|
||||
© {new Date().getFullYear()} - Admin Dashboard
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,7 +7,7 @@ export default function GetUser() {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUser = async () => {
|
||||
try {
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { ReactNode, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { useAuth } from "@/hooks/useAuth"
|
||||
import { UserRole } from "@/config/routes.config"
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: ReactNode
|
||||
requiredRoles?: UserRole[]
|
||||
fallback?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Component để protect routes dựa trên role
|
||||
* Sử dụng ở client-side trong layouts hoặc pages
|
||||
*/
|
||||
export const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
|
||||
children,
|
||||
requiredRoles = [],
|
||||
fallback,
|
||||
}) => {
|
||||
const router = useRouter()
|
||||
const { isAuthenticated, userRoles, hasAnyRole } = useAuth()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
router.replace("/signin")
|
||||
}
|
||||
}, [isAuthenticated, router])
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (requiredRoles.length > 0 && !hasAnyRole(requiredRoles)) {
|
||||
if (fallback) {
|
||||
return <>{fallback}</>
|
||||
}
|
||||
router.replace("/error-403")
|
||||
return null
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper để render UI dựa trên role
|
||||
*/
|
||||
export const RoleGate: React.FC<{
|
||||
requiredRoles: UserRole[]
|
||||
children: ReactNode
|
||||
fallback?: ReactNode
|
||||
}> = ({ requiredRoles, children, fallback }) => {
|
||||
const { hasAnyRole } = useAuth()
|
||||
|
||||
if (!hasAnyRole(requiredRoles)) {
|
||||
return <>{fallback || null}</>
|
||||
}
|
||||
|
||||
return <>{children}</>
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import { API, HOME_URL } from "../../../api";
|
||||
import { setUserData } from "@/store/features/userSlice";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { saveUserToCookie } from "@/lib/cookieStorage";
|
||||
|
||||
export default function SignInForm() {
|
||||
const router = useRouter();
|
||||
@@ -74,15 +73,8 @@ export default function SignInForm() {
|
||||
|
||||
// console.log("Current User Data:", data);
|
||||
if (data?.data) {
|
||||
// Lưu user data vào Redux và cookies
|
||||
dispatch(setUserData(data.data));
|
||||
saveUserToCookie(data.data);
|
||||
|
||||
// Sử dụng window.location để force reload, đảm bảo cookie được set
|
||||
// và middleware check được cookie trước khi render page
|
||||
setTimeout(() => {
|
||||
window.location.href = "/";
|
||||
}, 100);
|
||||
router.push("/");
|
||||
}
|
||||
} else {
|
||||
toast.error("Email hoặc mật khẩu không đúng.");
|
||||
@@ -117,7 +109,7 @@ export default function SignInForm() {
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-5">
|
||||
<div className="grid grid-cols-1 gap-3 sm:gap-5">
|
||||
<button
|
||||
onClick={() => {
|
||||
const redirectUrl = HOME_URL;
|
||||
@@ -151,19 +143,6 @@ export default function SignInForm() {
|
||||
</svg>
|
||||
Sign in with Google
|
||||
</button>
|
||||
{/* <button className="inline-flex items-center justify-center gap-3 py-3 text-sm font-normal text-gray-700 transition-colors bg-gray-100 rounded-lg px-7 hover:bg-gray-200 hover:text-gray-800 dark:bg-white/5 dark:text-white/90 dark:hover:bg-white/10">
|
||||
<svg
|
||||
width="21"
|
||||
className="fill-current"
|
||||
height="20"
|
||||
viewBox="0 0 21 20"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M15.6705 1.875H18.4272L12.4047 8.75833L19.4897 18.125H13.9422L9.59717 12.4442L4.62554 18.125H1.86721L8.30887 10.7625L1.51221 1.875H7.20054L11.128 7.0675L15.6705 1.875ZM14.703 16.475H16.2305L6.37054 3.43833H4.73137L14.703 16.475Z" />
|
||||
</svg>
|
||||
Sign in with X
|
||||
</button> */}
|
||||
</div>
|
||||
<div className="relative py-3 sm:py-5">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
|
||||
@@ -150,7 +150,7 @@ export default function SignUpForm() {
|
||||
|
||||
{step === 1 && (
|
||||
<>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-5">
|
||||
<div className="grid grid-cols-1 gap-3 sm:gap-5">
|
||||
<button
|
||||
onClick={() => {
|
||||
const redirectUrl = HOME_URL;
|
||||
@@ -184,9 +184,6 @@ export default function SignUpForm() {
|
||||
</svg>
|
||||
Sign up with Google
|
||||
</button>
|
||||
{/* <button className="inline-flex items-center justify-center gap-3 py-3 text-sm font-normal text-gray-700 transition-colors bg-gray-100 rounded-lg px-7 hover:bg-gray-200 hover:text-gray-800 dark:bg-white/5 dark:text-white/90 dark:hover:bg-white/10">
|
||||
Sign up with X
|
||||
</button> */}
|
||||
</div>
|
||||
<div className="relative py-3 sm:py-5">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
|
||||
@@ -4,11 +4,14 @@ import Link from "next/link";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { Dropdown } from "../ui/dropdown/Dropdown";
|
||||
import { DropdownItem } from "../ui/dropdown/DropdownItem";
|
||||
import { fullDataUser } from "@/interface/admin";
|
||||
import { UserMetaCardProps } from "@/interface/user";
|
||||
import { apiGetCurrentUser, apiLogout } from "@/service/auth";
|
||||
import { removeUserFromCookie } from "@/lib/cookieStorage";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function UserDropdown() {
|
||||
const router = useRouter();
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [user, setUser] = useState<UserMetaCardProps | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
@@ -44,9 +47,6 @@ export default function UserDropdown() {
|
||||
} catch (error) {
|
||||
console.error("Logout failed", error);
|
||||
} finally {
|
||||
// Xóa user data từ cookies
|
||||
removeUserFromCookie();
|
||||
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
/**
|
||||
* Role-Based Access Control Configuration
|
||||
* Định nghĩa routes theo role và quyền truy cập
|
||||
*/
|
||||
|
||||
export type UserRole = "ADMIN" | "MOD" | "HISTORIAN" | "USER"
|
||||
|
||||
export interface RouteConfig {
|
||||
path: string
|
||||
allowedRoles: UserRole[]
|
||||
label?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Public routes - không cần authentication
|
||||
*/
|
||||
export const PUBLIC_ROUTES = [
|
||||
"/signin",
|
||||
"/signup",
|
||||
"/reset-password",
|
||||
"/error-403",
|
||||
"/error-404",
|
||||
"/error-500",
|
||||
]
|
||||
|
||||
|
||||
export const PROTECTED_ROUTES: RouteConfig[] = [
|
||||
// Dashboard
|
||||
{
|
||||
path: "/",
|
||||
allowedRoles: ["ADMIN", "MOD", "HISTORIAN", "USER"],
|
||||
label: "Dashboard",
|
||||
},
|
||||
|
||||
// Admin/MOD + Historian routes
|
||||
{
|
||||
path: "/user-table",
|
||||
allowedRoles: ["ADMIN", "MOD"],
|
||||
label: "User Management",
|
||||
},
|
||||
{
|
||||
path: "/applications-tables",
|
||||
allowedRoles: ["ADMIN", "MOD"],
|
||||
label: "Applications",
|
||||
},
|
||||
|
||||
// All authenticated users
|
||||
{
|
||||
path: "/profile",
|
||||
allowedRoles: ["ADMIN", "MOD", "HISTORIAN", "USER"],
|
||||
label: "User Profile",
|
||||
},
|
||||
{
|
||||
path: "/calendar",
|
||||
allowedRoles: ["ADMIN", "MOD", "HISTORIAN", "USER"],
|
||||
label: "Calendar",
|
||||
},
|
||||
{
|
||||
path: "/line-chart",
|
||||
allowedRoles: ["ADMIN", "MOD", "HISTORIAN", "USER"],
|
||||
label: "Line Chart",
|
||||
},
|
||||
{
|
||||
path: "/bar-chart",
|
||||
allowedRoles: ["ADMIN", "MOD", "HISTORIAN", "USER"],
|
||||
label: "Bar Chart",
|
||||
},
|
||||
]
|
||||
|
||||
/**
|
||||
* Kiểm tra user role có được phép truy cập route không
|
||||
*/
|
||||
export const canAccessRoute = (
|
||||
userRoles: UserRole[] | undefined,
|
||||
routePath: string
|
||||
): boolean => {
|
||||
// Nếu không có role, không được truy cập
|
||||
if (!userRoles || userRoles.length === 0) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Public routes không cần check
|
||||
if (PUBLIC_ROUTES.includes(routePath)) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Tìm route config theo độ dài path giảm dần để tránh route '/' khớp với tất cả
|
||||
const routeConfig = PROTECTED_ROUTES
|
||||
.slice()
|
||||
.sort((a, b) => b.path.length - a.path.length)
|
||||
.find(
|
||||
(route) =>
|
||||
routePath === route.path ||
|
||||
(route.path !== "/" && routePath.startsWith(route.path + "/"))
|
||||
)
|
||||
|
||||
// Nếu route không được định nghĩa, cho phép (mặc định)
|
||||
if (!routeConfig) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check xem user có role được phép không
|
||||
return userRoles.some((role) => routeConfig.allowedRoles.includes(role))
|
||||
}
|
||||
|
||||
/**
|
||||
* Lấy danh sách routes cho user role
|
||||
*/
|
||||
export const getAvailableRoutes = (userRoles: UserRole[] | undefined): RouteConfig[] => {
|
||||
if (!userRoles || userRoles.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
return PROTECTED_ROUTES.filter((route) =>
|
||||
userRoles.some((role) => route.allowedRoles.includes(role))
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Kiểm tra user có role nào không
|
||||
*/
|
||||
export const hasRole = (userRoles: UserRole[] | undefined, role: UserRole): boolean => {
|
||||
return userRoles?.includes(role) ?? false
|
||||
}
|
||||
|
||||
/**
|
||||
* Kiểm tra user có ít nhất một trong các role không
|
||||
*/
|
||||
export const hasAnyRole = (
|
||||
userRoles: UserRole[] | undefined,
|
||||
roles: UserRole[]
|
||||
): boolean => {
|
||||
return userRoles?.some((role) => roles.includes(role)) ?? false
|
||||
}
|
||||
|
||||
/**
|
||||
* Kiểm tra user có tất cả các role không
|
||||
*/
|
||||
export const hasAllRoles = (
|
||||
userRoles: UserRole[] | undefined,
|
||||
roles: UserRole[]
|
||||
): boolean => {
|
||||
return roles.every((role) => userRoles?.includes(role))
|
||||
}
|
||||
@@ -51,6 +51,7 @@ export const SidebarProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
const toggleSidebar = () => {
|
||||
setIsExpanded((prev) => !prev);
|
||||
};
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useAppSelector } from '@/store/store';
|
||||
|
||||
import {
|
||||
canAccessRoute,
|
||||
hasRole,
|
||||
hasAnyRole,
|
||||
hasAllRoles,
|
||||
getAvailableRoutes,
|
||||
UserRole,
|
||||
} from "@/config/routes.config"
|
||||
|
||||
/**
|
||||
* Hook để kiểm tra authentication và authorization
|
||||
*/
|
||||
export const useAuth = () => {
|
||||
const user = useAppSelector((state) => state.user.data)
|
||||
const isAuthenticated = useAppSelector((state) => state.user.isAuthenticated)
|
||||
|
||||
const userRoles = user?.roles?.map((r) => r.name) as UserRole[] | undefined
|
||||
|
||||
return {
|
||||
user,
|
||||
isAuthenticated,
|
||||
userRoles,
|
||||
|
||||
/**
|
||||
* Kiểm tra user có role cụ thể không
|
||||
*/
|
||||
hasRole: (role: UserRole) => hasRole(userRoles, role),
|
||||
|
||||
/**
|
||||
* Kiểm tra user có ít nhất một trong các role không
|
||||
*/
|
||||
hasAnyRole: (roles: UserRole[]) => hasAnyRole(userRoles, roles),
|
||||
|
||||
/**
|
||||
* Kiểm tra user có tất cả các role không
|
||||
*/
|
||||
hasAllRoles: (roles: UserRole[]) => hasAllRoles(userRoles, roles),
|
||||
|
||||
/**
|
||||
* Kiểm tra user có quyền truy cập route không
|
||||
*/
|
||||
canAccessRoute: (path: string) => canAccessRoute(userRoles, path),
|
||||
|
||||
/**
|
||||
* Kiểm tra user là admin
|
||||
*/
|
||||
isAdmin: () => hasRole(userRoles, "ADMIN"),
|
||||
|
||||
/**
|
||||
* Kiểm tra user là moderator
|
||||
*/
|
||||
isModerator: () => hasRole(userRoles, "MOD"),
|
||||
|
||||
/**
|
||||
* Kiểm tra user là historian
|
||||
*/
|
||||
isHistorian: () => hasRole(userRoles, "HISTORIAN"),
|
||||
|
||||
/**
|
||||
* Lấy danh sách routes user có thể truy cập
|
||||
*/
|
||||
getAvailableRoutes: () => getAvailableRoutes(userRoles),
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect } from "react"
|
||||
import { useDispatch } from "react-redux"
|
||||
import { setUserData, clearUserData } from "@/store/features/userSlice"
|
||||
import { getUserFromCookie } from "@/lib/cookieStorage"
|
||||
|
||||
export const useRestoreUserData = () => {
|
||||
const dispatch = useDispatch()
|
||||
|
||||
useEffect(() => {
|
||||
const userData = getUserFromCookie()
|
||||
if (userData) {
|
||||
dispatch(setUserData(userData))
|
||||
} else {
|
||||
dispatch(clearUserData())
|
||||
}
|
||||
}, [dispatch])
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
"use client";
|
||||
import React, { useEffect, useRef, useState, useCallback } from "react";
|
||||
import React, { useEffect, useRef, useState, useCallback, useMemo } from "react";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useSelector } from "react-redux";
|
||||
import { RootState } from "@/store/store";
|
||||
import { useSidebar } from "../context/SidebarContext";
|
||||
import {
|
||||
BoxCubeIcon,
|
||||
@@ -17,18 +19,24 @@ import {
|
||||
TableIcon,
|
||||
UserCircleIcon,
|
||||
} from "../icons/index";
|
||||
import SidebarWidget from "./SidebarWidget";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { canAccessRoute, PUBLIC_ROUTES } from "@/config/routes.config";
|
||||
|
||||
type RoleName = "ADMIN" | "MOD" | "USER" | "HISTORIAN";
|
||||
|
||||
type NavItem = {
|
||||
name: string;
|
||||
icon: React.ReactNode;
|
||||
path?: string;
|
||||
subItems?: { name: string; path: string; pro?: boolean; new?: boolean }[];
|
||||
roles?: RoleName[];
|
||||
subItems?: {
|
||||
name: string;
|
||||
path: string;
|
||||
pro?: boolean;
|
||||
new?: boolean;
|
||||
roles?: RoleName[];
|
||||
}[];
|
||||
};
|
||||
|
||||
const navItems: NavItem[] = [
|
||||
const ALL_NAV_ITEMS: NavItem[] = [
|
||||
{
|
||||
icon: <GridIcon />,
|
||||
name: "Dashboard",
|
||||
@@ -44,19 +52,21 @@ const navItems: NavItem[] = [
|
||||
name: "User Profile",
|
||||
path: "/profile",
|
||||
},
|
||||
|
||||
{
|
||||
name: "Forms",
|
||||
icon: <ListIcon />,
|
||||
subItems: [{ name: "Form Elements", path: "/form-elements", pro: false }, { name: "Role Upgrade", path: "/role-upgrade", pro: false }],
|
||||
subItems: [
|
||||
// { name: "Form Elements", path: "/form-elements", pro: false },
|
||||
{ name: "Role Upgrade", path: "/role-upgrade", pro: false }
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "Tables",
|
||||
icon: <TableIcon />,
|
||||
subItems: [
|
||||
{ name: "Basic Tables", path: "/basic-tables", pro: false },
|
||||
{ name: "User Tables", path: "/user-table", pro: false },
|
||||
{ name: "Applications Tables", path: "/applications-tables", pro: false },
|
||||
// { name: "Basic Tables", path: "/basic-tables", pro: false },
|
||||
{ name: "User Tables", path: "/user-table", pro: false, roles: ["ADMIN", "MOD"] },
|
||||
{ name: "Applications Tables", path: "/applications-tables", pro: false, roles: ["ADMIN", "MOD"] },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -69,7 +79,7 @@ const navItems: NavItem[] = [
|
||||
},
|
||||
];
|
||||
|
||||
const othersItems: NavItem[] = [
|
||||
const OTHERS_ITEMS: NavItem[] = [
|
||||
{
|
||||
icon: <PieChartIcon />,
|
||||
name: "Charts",
|
||||
@@ -103,98 +113,110 @@ const othersItems: NavItem[] = [
|
||||
const AppSidebar: React.FC = () => {
|
||||
const { isExpanded, isMobileOpen, isHovered, setIsHovered } = useSidebar();
|
||||
const pathname = usePathname();
|
||||
const { userRoles } = useAuth();
|
||||
|
||||
const hasAccess = (path?: string) => {
|
||||
if (!path) return true;
|
||||
if (!userRoles || userRoles.length === 0) {
|
||||
return PUBLIC_ROUTES.includes(path) || ["/", "/profile", "/calendar"].includes(path);
|
||||
}
|
||||
return canAccessRoute(userRoles, path);
|
||||
// Lấy data gốc từ Redux (không bị render lại vô cớ)
|
||||
const rolesData = useSelector((state: RootState) => state.user.data?.roles);
|
||||
|
||||
const userRoles = useMemo(() => {
|
||||
return rolesData?.map((r: any) => r.name) || [];
|
||||
}, [rolesData]);
|
||||
|
||||
const filterMenuByRole = useCallback((items: NavItem[]) => {
|
||||
return items
|
||||
.map((item) => ({
|
||||
...item,
|
||||
subItems: item.subItems?.filter((sub) => {
|
||||
if (!sub.roles) return true;
|
||||
return sub.roles.some((role) => userRoles.includes(role));
|
||||
}),
|
||||
}))
|
||||
.filter((item) => {
|
||||
if (item.roles && !item.roles.some((role) => userRoles.includes(role))) return false;
|
||||
if (item.subItems && item.subItems.length === 0 && !item.path) return false;
|
||||
return true;
|
||||
});
|
||||
}, [userRoles]);
|
||||
|
||||
const filteredNavItems = useMemo(() => filterMenuByRole(ALL_NAV_ITEMS), [filterMenuByRole]);
|
||||
const filteredOthersItems = useMemo(() => filterMenuByRole(OTHERS_ITEMS), [filterMenuByRole]);
|
||||
|
||||
const [openSubmenu, setOpenSubmenu] = useState<{
|
||||
type: "main" | "others";
|
||||
index: number;
|
||||
} | null>(null);
|
||||
const [subMenuHeight, setSubMenuHeight] = useState<Record<string, number>>({});
|
||||
const subMenuRefs = useRef<Record<string, HTMLDivElement | null>>({});
|
||||
|
||||
const isActive = useCallback((path: string) => path === pathname, [pathname]);
|
||||
|
||||
const handleSubmenuToggle = (index: number, menuType: "main" | "others") => {
|
||||
setOpenSubmenu((prev) =>
|
||||
prev?.type === menuType && prev?.index === index ? null : { type: menuType, index }
|
||||
);
|
||||
};
|
||||
|
||||
const buildNavItems = (items: NavItem[]) =>
|
||||
items
|
||||
.map((nav) => {
|
||||
if (nav.path && !hasAccess(nav.path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (nav.subItems) {
|
||||
const filteredItems = nav.subItems.filter((subItem) =>
|
||||
hasAccess(subItem.path),
|
||||
);
|
||||
if (filteredItems.length === 0) {
|
||||
return null;
|
||||
useEffect(() => {
|
||||
let submenuMatched = false;
|
||||
[
|
||||
{ items: filteredNavItems, type: "main" },
|
||||
{ items: filteredOthersItems, type: "others" },
|
||||
].forEach(({ items, type }) => {
|
||||
items.forEach((nav, index) => {
|
||||
nav.subItems?.forEach((sub) => {
|
||||
if (isActive(sub.path)) {
|
||||
setOpenSubmenu((prev) => {
|
||||
if (prev?.type === type && prev?.index === index) return prev;
|
||||
return { type: type as "main" | "others", index };
|
||||
});
|
||||
submenuMatched = true;
|
||||
}
|
||||
return { ...nav, subItems: filteredItems };
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
return nav;
|
||||
})
|
||||
.filter((item): item is NavItem => item !== null);
|
||||
if (!submenuMatched) {
|
||||
setOpenSubmenu((prev) => (prev !== null ? null : prev));
|
||||
}
|
||||
}, [pathname, isActive, filteredNavItems, filteredOthersItems]);
|
||||
|
||||
const filteredMainNavItems = buildNavItems(navItems);
|
||||
const filteredOthersNavItems = buildNavItems(othersItems);
|
||||
useEffect(() => {
|
||||
if (openSubmenu !== null) {
|
||||
const key = `${openSubmenu.type}-${openSubmenu.index}`;
|
||||
if (subMenuRefs.current[key]) {
|
||||
setSubMenuHeight((prev) => ({
|
||||
...prev,
|
||||
[key]: subMenuRefs.current[key]?.scrollHeight || 0,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}, [openSubmenu]);
|
||||
|
||||
const renderMenuItems = (
|
||||
navItems: NavItem[],
|
||||
menuType: "main" | "others",
|
||||
) => (
|
||||
const renderMenuItems = (items: NavItem[], menuType: "main" | "others") => (
|
||||
<ul className="flex flex-col gap-4">
|
||||
{navItems.map((nav, index) => (
|
||||
{items.map((nav, index) => (
|
||||
<li key={nav.name}>
|
||||
{nav.subItems ? (
|
||||
<button
|
||||
onClick={() => handleSubmenuToggle(index, menuType)}
|
||||
className={`menu-item group ${
|
||||
className={`menu-item group ${
|
||||
openSubmenu?.type === menuType && openSubmenu?.index === index
|
||||
? "menu-item-active"
|
||||
: "menu-item-inactive"
|
||||
} cursor-pointer ${
|
||||
!isExpanded && !isHovered
|
||||
? "lg:justify-center"
|
||||
: "lg:justify-start"
|
||||
}`}
|
||||
? "menu-item-active" : "menu-item-inactive"
|
||||
} cursor-pointer ${!isExpanded && !isHovered ? "lg:justify-center" : "lg:justify-start"}`}
|
||||
>
|
||||
<span
|
||||
className={` ${
|
||||
openSubmenu?.type === menuType && openSubmenu?.index === index
|
||||
? "menu-item-icon-active"
|
||||
: "menu-item-icon-inactive"
|
||||
}`}
|
||||
>
|
||||
<span className={openSubmenu?.type === menuType && openSubmenu?.index === index ? "menu-item-icon-active" : "menu-item-icon-inactive"}>
|
||||
{nav.icon}
|
||||
</span>
|
||||
{(isExpanded || isHovered || isMobileOpen) && (
|
||||
<span className={`menu-item-text`}>{nav.name}</span>
|
||||
)}
|
||||
{(isExpanded || isHovered || isMobileOpen) && (
|
||||
<ChevronDownIcon
|
||||
className={`ml-auto w-5 h-5 transition-transform duration-200 ${
|
||||
openSubmenu?.type === menuType &&
|
||||
openSubmenu?.index === index
|
||||
? "rotate-180 text-brand-500"
|
||||
: ""
|
||||
}`}
|
||||
/>
|
||||
<>
|
||||
<span className={`menu-item-text`}>{nav.name}</span>
|
||||
<ChevronDownIcon className={`ml-auto w-5 h-5 transition-transform duration-200 ${openSubmenu?.type === menuType && openSubmenu?.index === index ? "rotate-180 text-brand-500" : ""}`} />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
nav.path && (
|
||||
<Link
|
||||
href={nav.path}
|
||||
className={`menu-item group ${
|
||||
isActive(nav.path) ? "menu-item-active" : "menu-item-inactive"
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`${
|
||||
isActive(nav.path)
|
||||
? "menu-item-icon-active"
|
||||
: "menu-item-icon-inactive"
|
||||
}`}
|
||||
>
|
||||
<Link href={nav.path} className={`menu-item group ${isActive(nav.path) ? "menu-item-active" : "menu-item-inactive"}`}>
|
||||
<span className={isActive(nav.path) ? "menu-item-icon-active" : "menu-item-icon-inactive"}>
|
||||
{nav.icon}
|
||||
</span>
|
||||
{(isExpanded || isHovered || isMobileOpen) && (
|
||||
@@ -205,52 +227,18 @@ const AppSidebar: React.FC = () => {
|
||||
)}
|
||||
{nav.subItems && (isExpanded || isHovered || isMobileOpen) && (
|
||||
<div
|
||||
ref={(el) => {
|
||||
subMenuRefs.current[`${menuType}-${index}`] = el;
|
||||
}}
|
||||
ref={(el) => { subMenuRefs.current[`${menuType}-${index}`] = el; }}
|
||||
className="overflow-hidden transition-all duration-300"
|
||||
style={{
|
||||
height:
|
||||
openSubmenu?.type === menuType && openSubmenu?.index === index
|
||||
? `${subMenuHeight[`${menuType}-${index}`]}px`
|
||||
: "0px",
|
||||
}}
|
||||
style={{ height: openSubmenu?.type === menuType && openSubmenu?.index === index ? `${subMenuHeight[`${menuType}-${index}`]}px` : "0px" }}
|
||||
>
|
||||
<ul className="mt-2 space-y-1 ml-9">
|
||||
{nav.subItems.map((subItem) => (
|
||||
<li key={subItem.name}>
|
||||
<Link
|
||||
href={subItem.path}
|
||||
className={`menu-dropdown-item ${
|
||||
isActive(subItem.path)
|
||||
? "menu-dropdown-item-active"
|
||||
: "menu-dropdown-item-inactive"
|
||||
}`}
|
||||
>
|
||||
<Link href={subItem.path} className={`menu-dropdown-item ${isActive(subItem.path) ? "menu-dropdown-item-active" : "menu-dropdown-item-inactive"}`}>
|
||||
{subItem.name}
|
||||
<span className="flex items-center gap-1 ml-auto">
|
||||
{subItem.new && (
|
||||
<span
|
||||
className={`ml-auto ${
|
||||
isActive(subItem.path)
|
||||
? "menu-dropdown-badge-active"
|
||||
: "menu-dropdown-badge-inactive"
|
||||
} menu-dropdown-badge `}
|
||||
>
|
||||
new
|
||||
</span>
|
||||
)}
|
||||
{subItem.pro && (
|
||||
<span
|
||||
className={`ml-auto ${
|
||||
isActive(subItem.path)
|
||||
? "menu-dropdown-badge-active"
|
||||
: "menu-dropdown-badge-inactive"
|
||||
} menu-dropdown-badge `}
|
||||
>
|
||||
pro
|
||||
</span>
|
||||
)}
|
||||
{subItem.new && <span className={`${isActive(subItem.path) ? "menu-dropdown-badge-active" : "menu-dropdown-badge-inactive"} menu-dropdown-badge`}>new</span>}
|
||||
{subItem.pro && <span className={`${isActive(subItem.path) ? "menu-dropdown-badge-active" : "menu-dropdown-badge-inactive"} menu-dropdown-badge`}>pro</span>}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
@@ -263,160 +251,44 @@ const AppSidebar: React.FC = () => {
|
||||
</ul>
|
||||
);
|
||||
|
||||
const [openSubmenu, setOpenSubmenu] = useState<{
|
||||
type: "main" | "others";
|
||||
index: number;
|
||||
} | null>(null);
|
||||
const [subMenuHeight, setSubMenuHeight] = useState<Record<string, number>>(
|
||||
{},
|
||||
);
|
||||
const subMenuRefs = useRef<Record<string, HTMLDivElement | null>>({});
|
||||
|
||||
// const isActive = (path: string) => path === pathname;
|
||||
const isActive = useCallback((path: string) => path === pathname, [pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
// Check if the current path matches any submenu item
|
||||
let submenuMatched = false;
|
||||
["main", "others"].forEach((menuType) => {
|
||||
const items = menuType === "main" ? navItems : othersItems;
|
||||
items.forEach((nav, index) => {
|
||||
if (nav.subItems) {
|
||||
nav.subItems.forEach((subItem) => {
|
||||
if (isActive(subItem.path)) {
|
||||
setOpenSubmenu({
|
||||
type: menuType as "main" | "others",
|
||||
index,
|
||||
});
|
||||
submenuMatched = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// If no submenu item matches, close the open submenu
|
||||
if (!submenuMatched) {
|
||||
setOpenSubmenu(null);
|
||||
}
|
||||
}, [pathname, isActive]);
|
||||
|
||||
useEffect(() => {
|
||||
// Set the height of the submenu items when the submenu is opened
|
||||
if (openSubmenu !== null) {
|
||||
const key = `${openSubmenu.type}-${openSubmenu.index}`;
|
||||
if (subMenuRefs.current[key]) {
|
||||
setSubMenuHeight((prevHeights) => ({
|
||||
...prevHeights,
|
||||
[key]: subMenuRefs.current[key]?.scrollHeight || 0,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}, [openSubmenu]);
|
||||
|
||||
const handleSubmenuToggle = (index: number, menuType: "main" | "others") => {
|
||||
setOpenSubmenu((prevOpenSubmenu) => {
|
||||
if (
|
||||
prevOpenSubmenu &&
|
||||
prevOpenSubmenu.type === menuType &&
|
||||
prevOpenSubmenu.index === index
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return { type: menuType, index };
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<aside
|
||||
className={`fixed mt-16 flex flex-col lg:mt-0 top-0 px-5 left-0 bg-white dark:bg-gray-900 dark:border-gray-800 text-gray-900 h-screen transition-all duration-300 ease-in-out z-50 border-r border-gray-200
|
||||
${
|
||||
isExpanded || isMobileOpen
|
||||
? "w-[290px]"
|
||||
: isHovered
|
||||
? "w-[290px]"
|
||||
: "w-[90px]"
|
||||
}
|
||||
${isMobileOpen ? "translate-x-0" : "-translate-x-full"}
|
||||
lg:translate-x-0`}
|
||||
${isExpanded || isMobileOpen ? "w-[290px]" : isHovered ? "w-[290px]" : "w-[90px]"}
|
||||
${isMobileOpen ? "translate-x-0" : "-translate-x-full"} lg:translate-x-0`}
|
||||
onMouseEnter={() => !isExpanded && setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<div
|
||||
className={`py-8 flex ${
|
||||
!isExpanded && !isHovered ? "lg:justify-center" : "justify-start"
|
||||
}`}
|
||||
>
|
||||
<div className={`py-8 flex ${!isExpanded && !isHovered ? "lg:justify-center" : "justify-start"}`}>
|
||||
<Link href="/">
|
||||
{isExpanded || isHovered || isMobileOpen ? (
|
||||
<>
|
||||
<Image
|
||||
className="dark:hidden"
|
||||
src="/images/logo/logo.svg"
|
||||
alt="Logo"
|
||||
width={80}
|
||||
height={50}
|
||||
/>
|
||||
<Image
|
||||
className="hidden dark:block"
|
||||
src="/images/logo/logo.svg"
|
||||
alt="Logo"
|
||||
width={150}
|
||||
height={40}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<Image
|
||||
src="/images/logo/logo.svg"
|
||||
alt="Logo"
|
||||
width={32}
|
||||
height={32}
|
||||
/>
|
||||
)}
|
||||
<Image
|
||||
src="/images/logo/logo.svg"
|
||||
alt="Logo"
|
||||
width={isExpanded || isHovered || isMobileOpen ? 80 : 32}
|
||||
height={isExpanded || isHovered || isMobileOpen ? 50 : 32}
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="flex flex-col overflow-y-auto duration-300 ease-linear no-scrollbar">
|
||||
<nav className="mb-6">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div>
|
||||
<h2
|
||||
className={`mb-4 text-xs uppercase flex leading-[20px] text-gray-400 ${
|
||||
!isExpanded && !isHovered
|
||||
? "lg:justify-center"
|
||||
: "justify-start"
|
||||
}`}
|
||||
>
|
||||
{isExpanded || isHovered || isMobileOpen ? (
|
||||
"Menu"
|
||||
) : (
|
||||
<HorizontaLDots />
|
||||
)}
|
||||
<h2 className={`mb-4 text-xs uppercase flex leading-[20px] text-gray-400 ${!isExpanded && !isHovered ? "lg:justify-center" : "justify-start"}`}>
|
||||
{isExpanded || isHovered || isMobileOpen ? "Menu" : <HorizontaLDots />}
|
||||
</h2>
|
||||
{renderMenuItems(filteredMainNavItems, "main")}
|
||||
{renderMenuItems(filteredNavItems, "main")}
|
||||
</div>
|
||||
|
||||
<div className="">
|
||||
<h2
|
||||
className={`mb-4 text-xs uppercase flex leading-[20px] text-gray-400 ${
|
||||
!isExpanded && !isHovered
|
||||
? "lg:justify-center"
|
||||
: "justify-start"
|
||||
}`}
|
||||
>
|
||||
{isExpanded || isHovered || isMobileOpen ? (
|
||||
"Others"
|
||||
) : (
|
||||
<HorizontaLDots />
|
||||
)}
|
||||
<div>
|
||||
<h2 className={`mb-4 text-xs uppercase flex leading-[20px] text-gray-400 ${!isExpanded && !isHovered ? "lg:justify-center" : "justify-start"}`}>
|
||||
{isExpanded || isHovered || isMobileOpen ? "Others" : <HorizontaLDots />}
|
||||
</h2>
|
||||
{renderMenuItems(filteredOthersNavItems, "others")}
|
||||
{renderMenuItems(filteredOthersItems, "others")}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
{/* {isExpanded || isHovered || isMobileOpen ? <SidebarWidget /> : null} */}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
};
|
||||
|
||||
export default AppSidebar;
|
||||
export default AppSidebar;
|
||||
@@ -1,37 +0,0 @@
|
||||
import { UserData } from "@/interface/user"
|
||||
|
||||
export const saveUserToCookie = (userData: UserData) => {
|
||||
if (typeof document === "undefined") return
|
||||
|
||||
const userDataJson = JSON.stringify(userData)
|
||||
document.cookie = `userDataRedux=${encodeURIComponent(userDataJson)}; path=/; max-age=86400`
|
||||
}
|
||||
|
||||
|
||||
export const removeUserFromCookie = () => {
|
||||
if (typeof document === "undefined") return
|
||||
|
||||
document.cookie = "userDataRedux=; path=/; max-age=0"
|
||||
}
|
||||
|
||||
export const getUserFromCookie = (): UserData | null => {
|
||||
if (typeof document === "undefined") return null
|
||||
|
||||
const name = "userDataRedux="
|
||||
const decodedCookie = decodeURIComponent(document.cookie)
|
||||
const cookieArray = decodedCookie.split(";")
|
||||
|
||||
for (let cookie of cookieArray) {
|
||||
cookie = cookie.trim()
|
||||
if (cookie.indexOf(name) === 0) {
|
||||
try {
|
||||
const userData = JSON.parse(cookie.substring(name.length))
|
||||
return userData
|
||||
} catch (error) {
|
||||
console.error("Error parsing user cookie:", error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -3,13 +3,6 @@
|
||||
import { useRef } from 'react';
|
||||
import { Provider } from 'react-redux';
|
||||
import { store } from './store';
|
||||
import { useRestoreUserData } from '@/hooks/useRestoreUserData';
|
||||
|
||||
|
||||
function RestoreUserDataComponent() {
|
||||
useRestoreUserData();
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function StoreProvider({
|
||||
children,
|
||||
@@ -17,10 +10,5 @@ export default function StoreProvider({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const storeRef = useRef(store);
|
||||
return (
|
||||
<Provider store={storeRef.current}>
|
||||
<RestoreUserDataComponent />
|
||||
{children}
|
||||
</Provider>
|
||||
);
|
||||
return <Provider store={storeRef.current}>{children}</Provider>;
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { UserData } from '@/interface/user';
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
||||
import { getUserFromCookie } from '@/lib/cookieStorage';
|
||||
|
||||
const getStoredApplication = () => {
|
||||
if (typeof window !== "undefined") {
|
||||
@@ -10,24 +9,15 @@ const getStoredApplication = () => {
|
||||
return null;
|
||||
};
|
||||
|
||||
const getStoredUserData = (): UserData | null => {
|
||||
if (typeof window === "undefined") {
|
||||
return null;
|
||||
}
|
||||
return getUserFromCookie();
|
||||
};
|
||||
|
||||
interface UserState {
|
||||
data: UserData | null;
|
||||
isAuthenticated: boolean;
|
||||
selectedApplication: any | null;
|
||||
}
|
||||
|
||||
const storedUserData = getStoredUserData();
|
||||
|
||||
const initialState: UserState = {
|
||||
data: storedUserData,
|
||||
isAuthenticated: Boolean(storedUserData),
|
||||
data: null,
|
||||
isAuthenticated: false,
|
||||
selectedApplication: getStoredApplication(),
|
||||
};
|
||||
|
||||
@@ -39,10 +29,6 @@ const userSlice = createSlice({
|
||||
state.data = action.payload;
|
||||
state.isAuthenticated = true;
|
||||
},
|
||||
clearUserData: (state) => {
|
||||
state.data = null;
|
||||
state.isAuthenticated = false;
|
||||
},
|
||||
setSelectedApplication: (state, action: PayloadAction<any>) => {
|
||||
state.selectedApplication = action.payload;
|
||||
if (typeof window !== "undefined") {
|
||||
@@ -58,5 +44,5 @@ const userSlice = createSlice({
|
||||
},
|
||||
});
|
||||
|
||||
export const { setUserData, clearUserData, setSelectedApplication, clearSelectedApplication } = userSlice.actions;
|
||||
export const { setUserData, setSelectedApplication, clearSelectedApplication } = userSlice.actions;
|
||||
export default userSlice.reducer;
|
||||
@@ -1,5 +1,4 @@
|
||||
import { configureStore } from '@reduxjs/toolkit';
|
||||
import { useDispatch, useSelector, TypedUseSelectorHook } from 'react-redux'; // Thêm dòng này
|
||||
import userReducer from './features/userSlice';
|
||||
|
||||
export const store = configureStore({
|
||||
@@ -9,7 +8,4 @@ export const store = configureStore({
|
||||
});
|
||||
|
||||
export type RootState = ReturnType<typeof store.getState>;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
|
||||
export const useAppDispatch = () => useDispatch<AppDispatch>();
|
||||
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
Reference in New Issue
Block a user