pig update: decentralization, format date time
All checks were successful
Build and Release / release (push) Successful in 27s
All checks were successful
Build and Release / release (push) Successful in 27s
This commit is contained in:
67
middleware.ts
Normal file
67
middleware.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
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 token (cookies)
|
||||
const token = request.cookies.get("token") || request.cookies.get("access_token")
|
||||
const userDataCookie = request.cookies.get("userDataRedux")
|
||||
|
||||
// 3. Nếu không có token, redirect về signin
|
||||
if (!token) {
|
||||
const signinUrl = new URL("/signin", request.url)
|
||||
signinUrl.searchParams.set("from", pathname)
|
||||
return NextResponse.redirect(signinUrl)
|
||||
}
|
||||
|
||||
// 4. Kiểm tra role-based access
|
||||
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ề dashboard hoặc 403 page
|
||||
return NextResponse.redirect(new URL("/error-403", request.url))
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error parsing user data in middleware:", error)
|
||||
// Nếu lỗi parse, vẫn cho qua (để tránh infinite redirect)
|
||||
return NextResponse.next()
|
||||
}
|
||||
}
|
||||
|
||||
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,6 +5,7 @@ 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,
|
||||
@@ -190,8 +191,9 @@ export default function HistorianApplicationPage() {
|
||||
console.log(tableData)
|
||||
// console.log("Pagination info:", pagination);
|
||||
return (
|
||||
<div>
|
||||
<PageBreadcrumb pageTitle="Quản lý hồ sơ" />
|
||||
<ProtectedRoute requiredRoles={["ADMIN", "MOD", "HISTORIAN"]}>
|
||||
<div>
|
||||
<PageBreadcrumb pageTitle="Quản lý hồ sơ" />
|
||||
|
||||
<div className="space-y-6">
|
||||
<ComponentCard
|
||||
@@ -218,7 +220,6 @@ 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>
|
||||
@@ -354,5 +355,6 @@ export default function HistorianApplicationPage() {
|
||||
onRefresh={fetchApplications}
|
||||
/>
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ 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";
|
||||
|
||||
@@ -32,7 +33,9 @@ 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 }[]>([]);
|
||||
@@ -143,7 +146,6 @@ 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,
|
||||
@@ -185,7 +187,7 @@ export default function UserTable() {
|
||||
};
|
||||
|
||||
const pagination = tableData?.pagination;
|
||||
|
||||
|
||||
// console.log(pagination);
|
||||
|
||||
const handleOpenDetail = (user: fullDataUser) => {
|
||||
@@ -251,192 +253,197 @@ export default function UserTable() {
|
||||
};
|
||||
|
||||
return (
|
||||
<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"
|
||||
<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"
|
||||
>
|
||||
<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
|
||||
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"
|
||||
/>
|
||||
</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>
|
||||
<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)}
|
||||
/>
|
||||
</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 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>
|
||||
|
||||
<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>
|
||||
|
||||
{/* 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"
|
||||
{pagination && pagination.total_pages > 1 && (
|
||||
<Pagination
|
||||
currentPage={pagination.current_page}
|
||||
totalPages={pagination.total_pages}
|
||||
onPageChange={(newPage) => setPage(newPage)}
|
||||
/>
|
||||
<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)}
|
||||
<UserDetailModal
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => setIsModalOpen(false)}
|
||||
user={selectedUser}
|
||||
onChangeRole={handleOpenRoleModal}
|
||||
onDelete={(u) => {
|
||||
handleDelete(u);
|
||||
setIsModalOpen(false);
|
||||
}}
|
||||
onRestore={(u) => {
|
||||
handleRestore(u);
|
||||
setIsModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
</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>
|
||||
<ChangeRoleModal
|
||||
isOpen={isRoleModalOpen}
|
||||
onClose={() => setIsRoleModalOpen(false)}
|
||||
user={roleUser}
|
||||
onSuccess={fetchUsers}
|
||||
/>
|
||||
</ComponentCard>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ProtectedRoute>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,18 @@ 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);
|
||||
@@ -214,55 +226,57 @@ 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 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>
|
||||
)}
|
||||
|
||||
<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">
|
||||
{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>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Lightbox
|
||||
|
||||
53
src/app/(full-width-pages)/(error-pages)/error-403/page.tsx
Normal file
53
src/app/(full-width-pages)/(error-pages)/error-403/page.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
62
src/components/auth/ProtectedRoute.tsx
Normal file
62
src/components/auth/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
"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,6 +12,7 @@ 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();
|
||||
@@ -73,7 +74,9 @@ 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);
|
||||
router.push("/");
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -4,14 +4,11 @@ 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 { useRouter } from "next/navigation";
|
||||
import { removeUserFromCookie } from "@/lib/cookieStorage";
|
||||
|
||||
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);
|
||||
@@ -47,6 +44,9 @@ export default function UserDropdown() {
|
||||
} catch (error) {
|
||||
console.error("Logout failed", error);
|
||||
} finally {
|
||||
// Xóa user data từ cookies
|
||||
removeUserFromCookie();
|
||||
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
|
||||
|
||||
144
src/config/routes.config.ts
Normal file
144
src/config/routes.config.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* 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))
|
||||
}
|
||||
66
src/hooks/useAuth.ts
Normal file
66
src/hooks/useAuth.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
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),
|
||||
}
|
||||
}
|
||||
19
src/hooks/useRestoreUserData.ts
Normal file
19
src/hooks/useRestoreUserData.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
"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])
|
||||
}
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
UserCircleIcon,
|
||||
} from "../icons/index";
|
||||
import SidebarWidget from "./SidebarWidget";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { canAccessRoute, PUBLIC_ROUTES } from "@/config/routes.config";
|
||||
|
||||
type NavItem = {
|
||||
name: string;
|
||||
@@ -101,6 +103,39 @@ 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);
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
return { ...nav, subItems: filteredItems };
|
||||
}
|
||||
|
||||
return nav;
|
||||
})
|
||||
.filter((item): item is NavItem => item !== null);
|
||||
|
||||
const filteredMainNavItems = buildNavItems(navItems);
|
||||
const filteredOthersNavItems = buildNavItems(othersItems);
|
||||
|
||||
const renderMenuItems = (
|
||||
navItems: NavItem[],
|
||||
@@ -357,7 +392,7 @@ const AppSidebar: React.FC = () => {
|
||||
<HorizontaLDots />
|
||||
)}
|
||||
</h2>
|
||||
{renderMenuItems(navItems, "main")}
|
||||
{renderMenuItems(filteredMainNavItems, "main")}
|
||||
</div>
|
||||
|
||||
<div className="">
|
||||
@@ -374,7 +409,7 @@ const AppSidebar: React.FC = () => {
|
||||
<HorizontaLDots />
|
||||
)}
|
||||
</h2>
|
||||
{renderMenuItems(othersItems, "others")}
|
||||
{renderMenuItems(filteredOthersNavItems, "others")}
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
37
src/lib/cookieStorage.ts
Normal file
37
src/lib/cookieStorage.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
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,6 +3,13 @@
|
||||
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,
|
||||
@@ -10,5 +17,10 @@ export default function StoreProvider({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const storeRef = useRef(store);
|
||||
return <Provider store={storeRef.current}>{children}</Provider>;
|
||||
return (
|
||||
<Provider store={storeRef.current}>
|
||||
<RestoreUserDataComponent />
|
||||
{children}
|
||||
</Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { UserData } from '@/interface/user';
|
||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
||||
import { getUserFromCookie } from '@/lib/cookieStorage';
|
||||
|
||||
const getStoredApplication = () => {
|
||||
if (typeof window !== "undefined") {
|
||||
@@ -9,15 +10,24 @@ 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: null,
|
||||
isAuthenticated: false,
|
||||
data: storedUserData,
|
||||
isAuthenticated: Boolean(storedUserData),
|
||||
selectedApplication: getStoredApplication(),
|
||||
};
|
||||
|
||||
@@ -29,6 +39,10 @@ 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") {
|
||||
@@ -44,5 +58,5 @@ const userSlice = createSlice({
|
||||
},
|
||||
});
|
||||
|
||||
export const { setUserData, setSelectedApplication, clearSelectedApplication } = userSlice.actions;
|
||||
export const { setUserData, clearUserData, setSelectedApplication, clearSelectedApplication } = userSlice.actions;
|
||||
export default userSlice.reducer;
|
||||
@@ -1,4 +1,5 @@
|
||||
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({
|
||||
@@ -8,4 +9,7 @@ export const store = configureStore({
|
||||
});
|
||||
|
||||
export type RootState = ReturnType<typeof store.getState>;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
export type AppDispatch = typeof store.dispatch;
|
||||
|
||||
export const useAppDispatch = () => useDispatch<AppDispatch>();
|
||||
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
|
||||
Reference in New Issue
Block a user