auth provider + private route
This commit is contained in:
+4
-53
@@ -1,24 +1,15 @@
|
|||||||
import FaJson from "@/langs/fa.json";
|
import FaJson from "@/langs/fa.json";
|
||||||
|
import { AuthProvider } from "@/context/AuthContext";
|
||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import i18next from "i18next";
|
import i18next from "i18next";
|
||||||
import { useEffect, useState, type FC } from "react";
|
import { type FC } from "react";
|
||||||
import { I18nextProvider } from "react-i18next";
|
import { I18nextProvider } from "react-i18next";
|
||||||
import "react-multi-date-picker/styles/layouts/mobile.css";
|
import "react-multi-date-picker/styles/layouts/mobile.css";
|
||||||
import { BrowserRouter } from "react-router-dom";
|
import { BrowserRouter } from "react-router-dom";
|
||||||
import "./assets/fonts/irancell/style.css";
|
import "./assets/fonts/irancell/style.css";
|
||||||
import ToastContainer from "./components/Toast";
|
import ToastContainer from "./components/Toast";
|
||||||
import { getToken, setRefreshToken, setToken } from "./config/func";
|
|
||||||
import { Paths } from "./config/Paths";
|
|
||||||
import MainRouter from "./router/MainRouter";
|
import MainRouter from "./router/MainRouter";
|
||||||
|
|
||||||
const isViewerPathname = (pathname: string) => {
|
|
||||||
const viewerPathPrefix = `${Paths.viewer}/`;
|
|
||||||
return (
|
|
||||||
pathname.startsWith(viewerPathPrefix) &&
|
|
||||||
pathname.length > viewerPathPrefix.length
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
i18next.init({
|
i18next.init({
|
||||||
interpolation: { escapeValue: false },
|
interpolation: { escapeValue: false },
|
||||||
lng: "fa",
|
lng: "fa",
|
||||||
@@ -32,56 +23,16 @@ i18next.init({
|
|||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
const App: FC = () => {
|
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 (
|
return (
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
|
<AuthProvider>
|
||||||
<I18nextProvider i18n={i18next}>
|
<I18nextProvider i18n={i18next}>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<MainRouter />
|
<MainRouter />
|
||||||
<ToastContainer />
|
<ToastContainer />
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
</I18nextProvider>
|
</I18nextProvider>
|
||||||
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,3 +9,14 @@ export const Paths = {
|
|||||||
request: "/designer/request",
|
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)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import axios from "@/config/axios";
|
import axios from "@/config/axios";
|
||||||
import type {
|
|
||||||
CreateCatalogParamsType,
|
|
||||||
UpdateCatalogParamsType,
|
|
||||||
} from "../types/Types";
|
|
||||||
import type {
|
import type {
|
||||||
CatalogByIdResponseType,
|
CatalogByIdResponseType,
|
||||||
CatalogResponseType,
|
CatalogResponseType,
|
||||||
} from "@/pages/catalogue/types/Types";
|
} from "@/pages/catalogue/types/Types";
|
||||||
|
import type {
|
||||||
|
CreateCatalogParamsType,
|
||||||
|
UpdateCatalogParamsType,
|
||||||
|
} from "../types/Types";
|
||||||
|
|
||||||
export const createCatalog = async (params: CreateCatalogParamsType) => {
|
export const createCatalog = async (params: CreateCatalogParamsType) => {
|
||||||
const { data } = await axios.post("/admin/catalogue", params);
|
const { data } = await axios.post("/admin/catalogue", params);
|
||||||
@@ -20,7 +20,7 @@ export const getCatalogs = async () => {
|
|||||||
|
|
||||||
export const getCatalogById = async (id: string) => {
|
export const getCatalogById = async (id: string) => {
|
||||||
const { data } = await axios.get<CatalogByIdResponseType>(
|
const { data } = await axios.get<CatalogByIdResponseType>(
|
||||||
`/admin/catalogue/${id}`,
|
`/public/catalogue/${id}`,
|
||||||
);
|
);
|
||||||
return data;
|
return data;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import SideBar from '@/shared/SideBar'
|
|||||||
import Header from '@/shared/Header'
|
import Header from '@/shared/Header'
|
||||||
import { Route, Routes, useLocation } from 'react-router-dom'
|
import { Route, Routes, useLocation } from 'react-router-dom'
|
||||||
import { Paths } from '@/config/Paths'
|
import { Paths } from '@/config/Paths'
|
||||||
|
import PrivateRoute from '@/router/PrivateRoute'
|
||||||
import { clx } from '@/helpers/utils'
|
import { clx } from '@/helpers/utils'
|
||||||
import { useSharedStore } from '@/shared/store/sharedStore'
|
import { useSharedStore } from '@/shared/store/sharedStore'
|
||||||
import Home from '@/pages/home/Home'
|
import Home from '@/pages/home/Home'
|
||||||
@@ -46,11 +47,46 @@ const MainRouter = () => {
|
|||||||
)}>
|
)}>
|
||||||
<div className='flex-1 h-full flex min-h-0'>
|
<div className='flex-1 h-full flex min-h-0'>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path={Paths.home} element={<Home />} />
|
<Route
|
||||||
<Route path={Paths.editor + '/:id'} element={<Editor />} />
|
path={Paths.home}
|
||||||
<Route path={Paths.viewer + '/:id'} element={<Viewer />} />
|
element={
|
||||||
<Route path={Paths.catalog.list} element={<CatalogueList />} />
|
<PrivateRoute requireAuth={false}>
|
||||||
<Route path={Paths.designer.request} element={<DesignerRequest />} />
|
<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>
|
</Routes>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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
|
||||||
Reference in New Issue
Block a user