auth provider + private route

This commit is contained in:
hamid zarghami
2026-05-23 16:40:03 +03:30
parent 612deba297
commit cbdc7edbf5
6 changed files with 181 additions and 69 deletions
+10 -59
View File
@@ -1,24 +1,15 @@
import FaJson from "@/langs/fa.json";
import { AuthProvider } from "@/context/AuthContext";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import i18next from "i18next";
import { useEffect, useState, type FC } from "react";
import { type FC } from "react";
import { I18nextProvider } from "react-i18next";
import "react-multi-date-picker/styles/layouts/mobile.css";
import { BrowserRouter } from "react-router-dom";
import "./assets/fonts/irancell/style.css";
import ToastContainer from "./components/Toast";
import { getToken, setRefreshToken, setToken } from "./config/func";
import { Paths } from "./config/Paths";
import MainRouter from "./router/MainRouter";
const isViewerPathname = (pathname: string) => {
const viewerPathPrefix = `${Paths.viewer}/`;
return (
pathname.startsWith(viewerPathPrefix) &&
pathname.length > viewerPathPrefix.length
);
};
i18next.init({
interpolation: { escapeValue: false },
lng: "fa",
@@ -32,56 +23,16 @@ i18next.init({
const queryClient = new QueryClient();
const App: FC = () => {
const [isLogin, setIsLogin] = useState<"checking" | "isLogin" | "isNotLogin">(
"checking",
);
useEffect(() => {
// استخراج توکن‌ها از URL در صورت وجود
const urlParams = new URLSearchParams(window.location.search);
const tokenFromUrl = urlParams.get("token");
const refreshTokenFromUrl = urlParams.get("refreshToken");
if (tokenFromUrl && refreshTokenFromUrl) {
// ذخیره توکن‌ها (جایگزین کردن توکن‌های قبلی اگر وجود داشته باشند)
setToken(tokenFromUrl);
setRefreshToken(refreshTokenFromUrl);
// حذف پارامترها از URL
const newUrl = window.location.pathname;
window.history.replaceState({}, "", newUrl);
// تنظیم وضعیت لاگین و هدایت به صفحه اصلی
setIsLogin("isLogin");
// if (window.location.pathname === Paths.auth.login) {
// window.location.href = Paths.home
// }
return;
}
const token = getToken();
if (token) {
setIsLogin("isLogin");
} else if (isViewerPathname(window.location.pathname)) {
setIsLogin("isLogin");
} else {
setIsLogin("isNotLogin");
if (window.location.href.split("auth").length === 1) {
// window.location.href = Paths.auth.login
}
}
}, []);
console.log("isLogin", isLogin);
return (
<BrowserRouter>
<I18nextProvider i18n={i18next}>
<QueryClientProvider client={queryClient}>
<MainRouter />
<ToastContainer />
</QueryClientProvider>
</I18nextProvider>
<AuthProvider>
<I18nextProvider i18n={i18next}>
<QueryClientProvider client={queryClient}>
<MainRouter />
<ToastContainer />
</QueryClientProvider>
</I18nextProvider>
</AuthProvider>
</BrowserRouter>
);
};
+11
View File
@@ -9,3 +9,14 @@ export const Paths = {
request: "/designer/request",
},
};
const viewerPathPrefix = `${Paths.viewer}/`;
/** Routes that do not require login (must stay in sync with PrivateRoute requireAuth={false}) */
export const isPublicPath = (pathname: string): boolean => {
return (
pathname === Paths.home ||
(pathname.startsWith(viewerPathPrefix) &&
pathname.length > viewerPathPrefix.length)
);
};
+73
View File
@@ -0,0 +1,73 @@
import { getToken, setRefreshToken, setToken } from '@/config/func'
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type FC,
type ReactNode,
} from 'react'
export type AuthStatus = 'checking' | 'authenticated' | 'unauthenticated'
type AuthContextValue = {
status: AuthStatus
isAuthenticated: boolean
isChecking: boolean
refreshAuth: () => void
}
const AuthContext = createContext<AuthContextValue | null>(null)
type AuthProviderProps = {
children: ReactNode
}
export const AuthProvider: FC<AuthProviderProps> = ({ children }) => {
const [status, setStatus] = useState<AuthStatus>('checking')
const refreshAuth = useCallback(() => {
setStatus(getToken() ? 'authenticated' : 'unauthenticated')
}, [])
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search)
const tokenFromUrl = urlParams.get('token')
const refreshTokenFromUrl = urlParams.get('refreshToken')
if (tokenFromUrl && refreshTokenFromUrl) {
setToken(tokenFromUrl)
setRefreshToken(refreshTokenFromUrl)
const newUrl = window.location.pathname
window.history.replaceState({}, '', newUrl)
setStatus('authenticated')
return
}
refreshAuth()
}, [refreshAuth])
const value = useMemo<AuthContextValue>(
() => ({
status,
isAuthenticated: status === 'authenticated',
isChecking: status === 'checking',
refreshAuth,
}),
[status, refreshAuth],
)
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export const useAuth = (): AuthContextValue => {
const context = useContext(AuthContext)
if (!context) {
throw new Error('useAuth must be used within AuthProvider')
}
return context
}
+5 -5
View File
@@ -1,12 +1,12 @@
import axios from "@/config/axios";
import type {
CreateCatalogParamsType,
UpdateCatalogParamsType,
} from "../types/Types";
import type {
CatalogByIdResponseType,
CatalogResponseType,
} from "@/pages/catalogue/types/Types";
import type {
CreateCatalogParamsType,
UpdateCatalogParamsType,
} from "../types/Types";
export const createCatalog = async (params: CreateCatalogParamsType) => {
const { data } = await axios.post("/admin/catalogue", params);
@@ -20,7 +20,7 @@ export const getCatalogs = async () => {
export const getCatalogById = async (id: string) => {
const { data } = await axios.get<CatalogByIdResponseType>(
`/admin/catalogue/${id}`,
`/public/catalogue/${id}`,
);
return data;
};
+41 -5
View File
@@ -2,6 +2,7 @@ import SideBar from '@/shared/SideBar'
import Header from '@/shared/Header'
import { Route, Routes, useLocation } from 'react-router-dom'
import { Paths } from '@/config/Paths'
import PrivateRoute from '@/router/PrivateRoute'
import { clx } from '@/helpers/utils'
import { useSharedStore } from '@/shared/store/sharedStore'
import Home from '@/pages/home/Home'
@@ -46,11 +47,46 @@ const MainRouter = () => {
)}>
<div className='flex-1 h-full flex min-h-0'>
<Routes>
<Route path={Paths.home} element={<Home />} />
<Route path={Paths.editor + '/:id'} element={<Editor />} />
<Route path={Paths.viewer + '/:id'} element={<Viewer />} />
<Route path={Paths.catalog.list} element={<CatalogueList />} />
<Route path={Paths.designer.request} element={<DesignerRequest />} />
<Route
path={Paths.home}
element={
<PrivateRoute requireAuth={false}>
<Home />
</PrivateRoute>
}
/>
<Route
path={Paths.editor + '/:id'}
element={
<PrivateRoute>
<Editor />
</PrivateRoute>
}
/>
<Route
path={Paths.viewer + '/:id'}
element={
<PrivateRoute requireAuth={false}>
<Viewer />
</PrivateRoute>
}
/>
<Route
path={Paths.catalog.list}
element={
<PrivateRoute>
<CatalogueList />
</PrivateRoute>
}
/>
<Route
path={Paths.designer.request}
element={
<PrivateRoute>
<DesignerRequest />
</PrivateRoute>
}
/>
</Routes>
</div>
</div>
+41
View File
@@ -0,0 +1,41 @@
import { useAuth } from '@/context/AuthContext'
import { Paths } from '@/config/Paths'
import { type FC, type ReactNode } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
type PrivateRouteProps = {
children: ReactNode
/** When true (default), user must be logged in to access the route */
requireAuth?: boolean
/** Redirect target when auth is required but user is not logged in */
redirectTo?: string
}
const PrivateRoute: FC<PrivateRouteProps> = ({
children,
requireAuth = true,
redirectTo = Paths.home,
}) => {
const { isAuthenticated, isChecking } = useAuth()
const location = useLocation()
if (!requireAuth) {
return children
}
if (isChecking) {
return (
<div className="flex flex-1 items-center justify-center">
<div className="text-gray-600">در حال بارگذاری...</div>
</div>
)
}
if (!isAuthenticated) {
return <Navigate to={redirectTo} replace state={{ from: location }} />
}
return children
}
export default PrivateRoute