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 PageBreadcrumb from "@/components/common/PageBreadCrumb";
|
||||||
import Pagination from "@/components/tables/Pagination";
|
import Pagination from "@/components/tables/Pagination";
|
||||||
import Swal from "sweetalert2";
|
import Swal from "sweetalert2";
|
||||||
|
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
|
||||||
|
|
||||||
import ApplicationTable, {
|
import ApplicationTable, {
|
||||||
AppSortColumn,
|
AppSortColumn,
|
||||||
@@ -190,6 +191,7 @@ export default function HistorianApplicationPage() {
|
|||||||
console.log(tableData)
|
console.log(tableData)
|
||||||
// console.log("Pagination info:", pagination);
|
// console.log("Pagination info:", pagination);
|
||||||
return (
|
return (
|
||||||
|
<ProtectedRoute requiredRoles={["ADMIN", "MOD", "HISTORIAN"]}>
|
||||||
<div>
|
<div>
|
||||||
<PageBreadcrumb pageTitle="Quản lý hồ sơ" />
|
<PageBreadcrumb pageTitle="Quản lý hồ sơ" />
|
||||||
|
|
||||||
@@ -218,7 +220,6 @@ export default function HistorianApplicationPage() {
|
|||||||
</button>
|
</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 className="grid grid-cols-1 gap-4 mb-6 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="block mb-2 text-sm font-medium">Tìm kiếm</label>
|
<label className="block mb-2 text-sm font-medium">Tìm kiếm</label>
|
||||||
@@ -354,5 +355,6 @@ export default function HistorianApplicationPage() {
|
|||||||
onRefresh={fetchApplications}
|
onRefresh={fetchApplications}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
</ProtectedRoute>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
import { useEffect, useState, useCallback } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import Pagination from "@/components/tables/Pagination";
|
import Pagination from "@/components/tables/Pagination";
|
||||||
import { LIMIT_ITEM_TABLE } from "../../../../../../constant";
|
import { LIMIT_ITEM_TABLE } from "../../../../../../constant";
|
||||||
|
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
|
||||||
|
|
||||||
export type SortColumn = "created_at" | "updated_at" | "display_name" | "email";
|
export type SortColumn = "created_at" | "updated_at" | "display_name" | "email";
|
||||||
|
|
||||||
@@ -32,7 +33,9 @@ const formatDateTimeToISO = (
|
|||||||
|
|
||||||
export default function UserTable() {
|
export default function UserTable() {
|
||||||
const [page, setPage] = useState<number>(1);
|
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 [selectedRole, setSelectedRole] = useState<string>("");
|
||||||
const [roles, setRoles] = useState<{ id: string; name: string }[]>([]);
|
const [roles, setRoles] = useState<{ id: string; name: string }[]>([]);
|
||||||
@@ -143,7 +146,6 @@ export default function UserTable() {
|
|||||||
role_ids: selectedRole ? [selectedRole] : undefined,
|
role_ids: selectedRole ? [selectedRole] : undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Thêm format ngày giờ vào payload
|
|
||||||
const createdFrom = formatDateTimeToISO(
|
const createdFrom = formatDateTimeToISO(
|
||||||
debouncedParams.fromDate,
|
debouncedParams.fromDate,
|
||||||
debouncedParams.fromTime,
|
debouncedParams.fromTime,
|
||||||
@@ -251,6 +253,7 @@ export default function UserTable() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<ProtectedRoute requiredRoles={["ADMIN", "MOD"]}>
|
||||||
<div>
|
<div>
|
||||||
<PageBreadcrumb pageTitle="Quản lý người dùng" />
|
<PageBreadcrumb pageTitle="Quản lý người dùng" />
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@@ -316,7 +319,9 @@ export default function UserTable() {
|
|||||||
: e.target.value === "true",
|
: e.target.value === "true",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
value={isDeleted === undefined ? "" : isDeleted ? "true" : "false"}
|
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"
|
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="">Tất cả</option>
|
||||||
@@ -325,9 +330,10 @@ export default function UserTable() {
|
|||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Từ ngày */}
|
|
||||||
<div>
|
<div>
|
||||||
<label className="block mb-2 text-sm font-medium">Từ ngày</label>
|
<label className="block mb-2 text-sm font-medium">
|
||||||
|
Từ ngày
|
||||||
|
</label>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<input
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
@@ -344,9 +350,10 @@ export default function UserTable() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Đến ngày */}
|
|
||||||
<div>
|
<div>
|
||||||
<label className="block mb-2 text-sm font-medium">Đến ngày</label>
|
<label className="block mb-2 text-sm font-medium">
|
||||||
|
Đến ngày
|
||||||
|
</label>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<input
|
<input
|
||||||
type="date"
|
type="date"
|
||||||
@@ -363,7 +370,6 @@ export default function UserTable() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Limit */}
|
|
||||||
<div>
|
<div>
|
||||||
<label className="block mb-2 text-sm font-medium">
|
<label className="block mb-2 text-sm font-medium">
|
||||||
Số lượng (Limit)
|
Số lượng (Limit)
|
||||||
@@ -438,5 +444,6 @@ export default function UserTable() {
|
|||||||
</ComponentCard>
|
</ComponentCard>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</ProtectedRoute>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -38,6 +38,18 @@ export default function ApplicationDetailPage() {
|
|||||||
|
|
||||||
const config = statusConfig[application.status] || statusConfig.PENDING;
|
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 isImageFile = (file: any) => {
|
||||||
const isImageMime = file.mime_type?.startsWith("image/");
|
const isImageMime = file.mime_type?.startsWith("image/");
|
||||||
const isImageExt = /\.(jpg|jpeg|png|webp|gif)$/i.test(file.storage_key);
|
const isImageExt = /\.(jpg|jpeg|png|webp|gif)$/i.test(file.storage_key);
|
||||||
@@ -247,7 +259,7 @@ export default function ApplicationDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[11px] text-zinc-400 dark:text-zinc-500 tabular-nums">
|
<span className="text-[11px] text-zinc-400 dark:text-zinc-500 tabular-nums">
|
||||||
{application?.reviewed_at}
|
{formatDate(application?.reviewed_at)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -256,7 +268,9 @@ export default function ApplicationDetailPage() {
|
|||||||
{application?.review_note ? (
|
{application?.review_note ? (
|
||||||
<p>{application.review_note}</p>
|
<p>{application.review_note}</p>
|
||||||
) : (
|
) : (
|
||||||
<p className="italic text-zinc-500">Không có ghi chú bổ sung.</p>
|
<p className="italic text-zinc-500">
|
||||||
|
Không có ghi chú bổ sung.
|
||||||
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
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 { setUserData } from "@/store/features/userSlice";
|
||||||
import { useDispatch } from "react-redux";
|
import { useDispatch } from "react-redux";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { saveUserToCookie } from "@/lib/cookieStorage";
|
||||||
|
|
||||||
export default function SignInForm() {
|
export default function SignInForm() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -73,7 +74,9 @@ export default function SignInForm() {
|
|||||||
|
|
||||||
// console.log("Current User Data:", data);
|
// console.log("Current User Data:", data);
|
||||||
if (data?.data) {
|
if (data?.data) {
|
||||||
|
// Lưu user data vào Redux và cookies
|
||||||
dispatch(setUserData(data.data));
|
dispatch(setUserData(data.data));
|
||||||
|
saveUserToCookie(data.data);
|
||||||
router.push("/");
|
router.push("/");
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -4,14 +4,11 @@ import Link from "next/link";
|
|||||||
import React, { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { Dropdown } from "../ui/dropdown/Dropdown";
|
import { Dropdown } from "../ui/dropdown/Dropdown";
|
||||||
import { DropdownItem } from "../ui/dropdown/DropdownItem";
|
import { DropdownItem } from "../ui/dropdown/DropdownItem";
|
||||||
import { fullDataUser } from "@/interface/admin";
|
|
||||||
import { UserMetaCardProps } from "@/interface/user";
|
import { UserMetaCardProps } from "@/interface/user";
|
||||||
import { apiGetCurrentUser, apiLogout } from "@/service/auth";
|
import { apiGetCurrentUser, apiLogout } from "@/service/auth";
|
||||||
import { useRouter } from "next/navigation";
|
import { removeUserFromCookie } from "@/lib/cookieStorage";
|
||||||
|
|
||||||
export default function UserDropdown() {
|
export default function UserDropdown() {
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [user, setUser] = useState<UserMetaCardProps | null>(null);
|
const [user, setUser] = useState<UserMetaCardProps | null>(null);
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
@@ -47,6 +44,9 @@ export default function UserDropdown() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Logout failed", error);
|
console.error("Logout failed", error);
|
||||||
} finally {
|
} finally {
|
||||||
|
// Xóa user data từ cookies
|
||||||
|
removeUserFromCookie();
|
||||||
|
|
||||||
localStorage.clear();
|
localStorage.clear();
|
||||||
sessionStorage.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,
|
UserCircleIcon,
|
||||||
} from "../icons/index";
|
} from "../icons/index";
|
||||||
import SidebarWidget from "./SidebarWidget";
|
import SidebarWidget from "./SidebarWidget";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { canAccessRoute, PUBLIC_ROUTES } from "@/config/routes.config";
|
||||||
|
|
||||||
type NavItem = {
|
type NavItem = {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -101,6 +103,39 @@ const othersItems: NavItem[] = [
|
|||||||
const AppSidebar: React.FC = () => {
|
const AppSidebar: React.FC = () => {
|
||||||
const { isExpanded, isMobileOpen, isHovered, setIsHovered } = useSidebar();
|
const { isExpanded, isMobileOpen, isHovered, setIsHovered } = useSidebar();
|
||||||
const pathname = usePathname();
|
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 = (
|
const renderMenuItems = (
|
||||||
navItems: NavItem[],
|
navItems: NavItem[],
|
||||||
@@ -357,7 +392,7 @@ const AppSidebar: React.FC = () => {
|
|||||||
<HorizontaLDots />
|
<HorizontaLDots />
|
||||||
)}
|
)}
|
||||||
</h2>
|
</h2>
|
||||||
{renderMenuItems(navItems, "main")}
|
{renderMenuItems(filteredMainNavItems, "main")}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="">
|
<div className="">
|
||||||
@@ -374,7 +409,7 @@ const AppSidebar: React.FC = () => {
|
|||||||
<HorizontaLDots />
|
<HorizontaLDots />
|
||||||
)}
|
)}
|
||||||
</h2>
|
</h2>
|
||||||
{renderMenuItems(othersItems, "others")}
|
{renderMenuItems(filteredOthersNavItems, "others")}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</nav>
|
</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 { useRef } from 'react';
|
||||||
import { Provider } from 'react-redux';
|
import { Provider } from 'react-redux';
|
||||||
import { store } from './store';
|
import { store } from './store';
|
||||||
|
import { useRestoreUserData } from '@/hooks/useRestoreUserData';
|
||||||
|
|
||||||
|
|
||||||
|
function RestoreUserDataComponent() {
|
||||||
|
useRestoreUserData();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
export default function StoreProvider({
|
export default function StoreProvider({
|
||||||
children,
|
children,
|
||||||
@@ -10,5 +17,10 @@ export default function StoreProvider({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const storeRef = useRef(store);
|
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 { UserData } from '@/interface/user';
|
||||||
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
|
||||||
|
import { getUserFromCookie } from '@/lib/cookieStorage';
|
||||||
|
|
||||||
const getStoredApplication = () => {
|
const getStoredApplication = () => {
|
||||||
if (typeof window !== "undefined") {
|
if (typeof window !== "undefined") {
|
||||||
@@ -9,15 +10,24 @@ const getStoredApplication = () => {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getStoredUserData = (): UserData | null => {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return getUserFromCookie();
|
||||||
|
};
|
||||||
|
|
||||||
interface UserState {
|
interface UserState {
|
||||||
data: UserData | null;
|
data: UserData | null;
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
selectedApplication: any | null;
|
selectedApplication: any | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const storedUserData = getStoredUserData();
|
||||||
|
|
||||||
const initialState: UserState = {
|
const initialState: UserState = {
|
||||||
data: null,
|
data: storedUserData,
|
||||||
isAuthenticated: false,
|
isAuthenticated: Boolean(storedUserData),
|
||||||
selectedApplication: getStoredApplication(),
|
selectedApplication: getStoredApplication(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -29,6 +39,10 @@ const userSlice = createSlice({
|
|||||||
state.data = action.payload;
|
state.data = action.payload;
|
||||||
state.isAuthenticated = true;
|
state.isAuthenticated = true;
|
||||||
},
|
},
|
||||||
|
clearUserData: (state) => {
|
||||||
|
state.data = null;
|
||||||
|
state.isAuthenticated = false;
|
||||||
|
},
|
||||||
setSelectedApplication: (state, action: PayloadAction<any>) => {
|
setSelectedApplication: (state, action: PayloadAction<any>) => {
|
||||||
state.selectedApplication = action.payload;
|
state.selectedApplication = action.payload;
|
||||||
if (typeof window !== "undefined") {
|
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;
|
export default userSlice.reducer;
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { configureStore } from '@reduxjs/toolkit';
|
import { configureStore } from '@reduxjs/toolkit';
|
||||||
|
import { useDispatch, useSelector, TypedUseSelectorHook } from 'react-redux'; // Thêm dòng này
|
||||||
import userReducer from './features/userSlice';
|
import userReducer from './features/userSlice';
|
||||||
|
|
||||||
export const store = configureStore({
|
export const store = configureStore({
|
||||||
@@ -9,3 +10,6 @@ export const store = configureStore({
|
|||||||
|
|
||||||
export type RootState = ReturnType<typeof store.getState>;
|
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