add auth and base functions and fixed bug

This commit is contained in:
Amirhossein Mahmoodi
2024-07-09 11:28:59 +03:30
parent 6288ac926c
commit 863bdaca95
23 changed files with 592 additions and 69 deletions

View File

@@ -0,0 +1 @@
NEXT_PUBLIC_API_URL="https://rms.witel.ir"

View File

@@ -16,6 +16,7 @@
"@mui/material": "^5.15.6",
"@mui/material-nextjs": "^5.15.6",
"@mui/x-date-pickers": "^6.19.5",
"axios": "^1.7.2",
"date-fns": "^3.3.1",
"date-fns-jalali": "^2.13.0-0",
"dayjs": "^1.11.10",

View File

@@ -1,7 +1,9 @@
@import "fontiran";
@import "react-toastify/dist/ReactToastify.css";
.filter-toast {
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px,
rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
background-color: #d0dfe8;
border: 1px dashed #095b8c;
}

View File

@@ -1,11 +0,0 @@
import 'react-toastify/dist/ReactToastify.css';
const Layout = ({children}) => {
return (
<>
{children}
</>
)
}
export default Layout

View File

@@ -1,6 +1,28 @@
'use client'
import { Button } from "@mui/material"
import axios from "axios"
const Page = () => {
const handler = () => {
try {
axios.get('https://rms.witel.ir/test_login?username=witel', { withCredentials: true })
} catch (error) {
console.log(error);
}
}
const handler2 = () => {
try {
const res = axios.get('https://rms.witel.ir/webapi/user/get-permission', { withCredentials: true })
console.log(res);
} catch (error) {
console.log(error);
}
}
return (
<div>dashboard</div>
<>
<Button onClick={handler}>login</Button>
<Button onClick={handler2}>check</Button>
</>
)
}

View File

@@ -1,17 +1,19 @@
import {Box, Stack} from "@mui/material";
import { Box, Stack } from "@mui/material";
import HeaderWithLogo from "@/components/layouts/dashboard/headerWithLogo";
import HeaderWithSidebar from "@/components/layouts/dashboard/headerWithSidebar";
import 'react-toastify/dist/ReactToastify.css';
const Template = ({children}) => {
return (<Stack>
<HeaderWithLogo/>
const Template = ({ children }) => {
return (
<Stack>
<HeaderWithLogo />
<Box>
<HeaderWithSidebar>
{children}
</HeaderWithSidebar>
</Box>
</Stack>)
</Stack>
)
}
export default Template

View File

@@ -0,0 +1,14 @@
import WithAuthMiddleware from "@/core/middlewares/withAuth"
import { AuthProvider } from "@/lib/contexts/auth"
const Layout = ({ children }) => {
return (
<AuthProvider>
<WithAuthMiddleware>
{children}
</WithAuthMiddleware>
</AuthProvider>
)
}
export default Layout

View File

@@ -1,13 +1,13 @@
import {TableSettingProvider} from "@/lib/contexts/tableSetting";
import { TableSettingProvider } from "@/lib/contexts/tableSetting";
export const metadata = {
title: 'سامانه جامع راهداری',
}
export default function RootLayout({children}) {
export default function RootLayout({ children }) {
return (
<html lang="fa" dir={'rtl'}>
<body style={{height: '100vh'}}>
<body style={{ height: '100vh' }}>
<TableSettingProvider>
{children}
</TableSettingProvider>

51
src/app/lfwd/page.js Normal file
View File

@@ -0,0 +1,51 @@
'use client'
import { GET_LOGIN_ROUTE } from "@/core/utils/routes"
import useRequest from "@/lib/hooks/useRequest"
import { Button, Stack, Typography, Zoom } from "@mui/material"
import Link from "next/link"
import { useEffect, useState } from "react"
const Page = () => {
const [login, setLogin] = useState(0)
const request = useRequest()
useEffect(() => {
const login = async () => {
try {
const res = await request(`${GET_LOGIN_ROUTE}?username=witel`)
setLogin(1)
} catch (error) {
setLogin(2)
}
}
login()
}, [])
const retry = async () => {
setLogin(0)
try {
const res = await request(`${GET_LOGIN_ROUTE}?username=witel`)
setLogin(1)
} catch (error) {
setLogin(2)
}
}
return (
<Stack alignItems={'center'} justifyContent={'center'} sx={{ height: '100%' }} spacing={2}>
<Typography variant="h5">
{login === 0 ? 'درحال دریافت مجوز برای ارتباط با سرور...' : login === 1 ? 'ارتباط با سرور برقرار شد.' : 'ارتباط با سرور برقرار نشد. مشکلی وجود دارد.'}
</Typography>
<Zoom in={login === 1}>
<Button component={Link} href="/">ورود به سامانه</Button>
</Zoom>
<Zoom in={login === 2}>
<Button onClick={retry}>تلاش مجدد</Button>
</Zoom>
</Stack>
)
}
export default Page

View File

@@ -1,18 +1,18 @@
import cacheProviderRtl from "@/core/utils/cacheRtl";
import {CssBaseline, ThemeProvider} from "@mui/material";
import { CssBaseline, ThemeProvider } from "@mui/material";
import theme from "@/core/utils/theme";
import {AppRouterCacheProvider} from "@mui/material-nextjs/v14-appRouter";
import 'react-toastify/dist/ReactToastify.css';
import { AppRouterCacheProvider } from "@mui/material-nextjs/v14-appRouter";
import "^/global.scss";
import {ToastContainer} from "react-toastify";
import { ToastContainer } from "react-toastify";
const Template = ({children}) => {
const Template = ({ children }) => {
return (
<AppRouterCacheProvider CacheProvider={cacheProviderRtl} options={{enableCssLayer: true}}>
<AppRouterCacheProvider CacheProvider={cacheProviderRtl} options={{ enableCssLayer: true }}>
<ThemeProvider theme={theme}>
<CssBaseline/>
<CssBaseline />
{children}
<ToastContainer rtl containerId="filtering" closeButton={false}/>
<ToastContainer rtl containerId="filtering" closeButton={false} />
<ToastContainer rtl containerId="request_data" />
</ThemeProvider>
</AppRouterCacheProvider>
)

View File

@@ -0,0 +1,191 @@
import { toast } from "react-toastify";
import { Box, Typography } from "@mui/material";
import { Dangerous } from "@mui/icons-material";
export const errorServerToast = (toastContainer) =>
toast.error(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Dangerous color="error" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{"The request failed due to an internal error."}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: 5000,
hideProgressBar: true,
pauseOnHover: true,
closeOnClick: false,
draggable: true,
}
);
export const errorUnauthorizedToast = (toastContainer) =>
toast.error(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Dangerous color="error" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{"The user is not authorized to make the request."}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: 3000,
hideProgressBar: true,
pauseOnHover: true,
closeOnClick: false,
draggable: true,
}
);
export const errorLogicToast = (message, toastContainer) =>
toast.error(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Dangerous color="error" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{message ||
"The request was well-formed but was unable to be followed due to semantic errors."}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: false,
closeOnClick: false,
draggable: false,
}
);
export const errorValidationToast = (message, toastContainer) =>
toast.error(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Dangerous color="error" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{message ||
"The request was well-formed but was unable to be followed due to semantic errors."}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: false,
closeOnClick: false,
draggable: false,
}
);
export const errorTooManyToast = (toastContainer) =>
toast.error(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Dangerous color="error" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{"Too many requests have been sent within a given time span."}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: false,
closeOnClick: false,
draggable: false,
}
);
export const errorClientToast = (toastContainer) =>
toast.error(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Dangerous color="error" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{
"The API request is invalid or improperly formed. Consequently, the API server could not understand the request."
}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: false,
closeOnClick: false,
draggable: false,
}
);

View File

@@ -0,0 +1,35 @@
import { toast } from "react-toastify";
import { Box, Typography } from "@mui/material";
import { Beenhere } from "@mui/icons-material";
export const successToast = (toastContainer) =>
toast.success(
() => (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
justifyContent: "start",
}}
>
<Box sx={{ display: "flex", alignItems: "center" }}>
<Beenhere color="success" sx={{ mr: 1.6 }} />
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="caption">
{"Your operation was successful"}
</Typography>
</Box>
</Box>
</Box>
),
{
icon: false,
containerId: toastContainer,
autoClose: 3000,
hideProgressBar: true,
pauseOnHover: true,
closeOnClick: false,
draggable: true,
}
);

View File

@@ -0,0 +1,22 @@
'use client'
import { useAuth } from "@/lib/contexts/auth";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
function WithAuthMiddleware({ children }) {
const router = useRouter()
const pathName = usePathname()
const { isAuth, initAuthState } = useAuth();
useEffect(() => {
if (!initAuthState) return
if (!isAuth) {
router.replace(`${process.env.NEXT_PUBLIC_API_URL}/login?_back=${encodeURIComponent(pathName)}`)
}
}, [isAuth, initAuthState])
if (!initAuthState || !isAuth) return null;
return <>{children}</>
}
export default WithAuthMiddleware

View File

@@ -0,0 +1,61 @@
'use client'
import { toast } from "react-toastify";
import {
errorClientToast,
errorLogicToast,
errorServerToast,
errorTooManyToast,
errorUnauthorizedToast,
errorValidationToast
} from "@/core/components/toasts/error";
const isServerError = status => status >= 500 && status <= 599;
const isClientError = status => status >= 400 && status <= 499;
const errorServer = (response, notification, toastContainer) => {
if (notification) errorServerToast(toastContainer)
}
const errorClient = (response, notification, toastContainer) => {
switch (response.status) {
case 401:
if (notification) errorUnauthorizedToast(toastContainer)
break;
case 422:
if ('type' in response.data) {
if (Array.isArray(response.data.message)) {
response.data.message.map((item) => {
if (notification) errorLogicToast(item, toastContainer)
})
} else {
if (notification) errorLogicToast(response.data.message, toastContainer)
}
break;
}
if (notification) {
const errorsMap = Object.keys(response.data.errors)
const errorsArray = response.data.errors
errorsMap.map((item, index) => {
errorValidationToast(errorsArray[item][0], toastContainer);
})
}
break;
case 429:
if (notification) errorTooManyToast(toastContainer)
break
default:
if (notification) errorClientToast(toastContainer)
break
}
}
export const errorResponse = (response, notification, toastContainer) => {
if (notification) toast.dismiss({ container: toastContainer })
if (isServerError(response.status)) {
errorServer(response, notification, toastContainer)
} else if (isClientError(response.status)) {
errorClient(response, notification, toastContainer)
}
}

View File

@@ -12,7 +12,7 @@ export const pageMenu = [
id: 'userManagement',
label: 'مدیریت کاربران',
type: "page",
route: "./v2/user_management",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/user_management",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
@@ -26,35 +26,35 @@ export const pageMenu = [
id: 'projectsManagmentFinance',
label: 'ثبت قرارداد و پروژه',
type: "page",
route: "./v2/rahdari_projects/finance",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/finance",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'projectsManagmentList',
label: 'لیست پروژه ها',
type: "page",
route: "./v2/rahdari_projects/projects_list",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/projects_list",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'projectsManagmentProposal',
label: 'پروژه های پیشنهادی',
type: "page",
route: "./v2/rahdari_projects/proposal",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/proposal",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'projectsManagmentLawmaker',
label: 'درخواست نمایندگان',
type: "page",
route: "./v2/rahdari_projects/lawmakers",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/lawmakers",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'projectsManagmentMap',
label: 'پراکندگی بر روی نقشه',
type: "page",
route: "./v2/map?type=rahdari_projects",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=rahdari_projects",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]
@@ -77,7 +77,7 @@ export const pageMenu = [
id: 'roadItemManagmentSupervisorCartable',
label: 'کارتابل',
type: "page",
route: "./v2/road_items/supervisor/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/supervisor/cartable",
},
]
},
@@ -92,13 +92,13 @@ export const pageMenu = [
id: 'roadItemManagmentOparationCreate',
label: 'ثبت فعالیت',
type: "page",
route: "./v2/road_items/operator/create",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/operator/create",
},
{
id: 'roadItemManagmentOparationCartable',
label: 'کارتابل',
type: "page",
route: "./v2/road_items/operator/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/operator/cartable",
},
]
},
@@ -106,14 +106,14 @@ export const pageMenu = [
id: 'roadItemManagmentMap',
label: 'پراکندگی بر روی نقشه',
type: "page",
route: "./v2/map?type=road_items",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_items",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'roadItemManagmentReport',
label: 'گزارش ها',
type: "page",
route: "./v2/road_items/report",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/report",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]
@@ -136,7 +136,7 @@ export const pageMenu = [
id: 'roadPatrolManagmentSupervisorCartable',
label: 'کارتابل',
type: "page",
route: "./road_patrols/supervisor/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/road_patrols/supervisor/cartable",
},
]
},
@@ -151,13 +151,13 @@ export const pageMenu = [
id: 'roadPatrolManagmentOparationCreate',
label: 'ثبت اقدام',
type: "page",
route: "./v2/road_patrols/operator/create",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/operator/create",
},
{
id: 'roadPatrolManagmentOparationCartable',
label: 'کارتابل',
type: "page",
route: "./v2/road_patrols/operator/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/operator/cartable",
},
]
},
@@ -165,14 +165,14 @@ export const pageMenu = [
id: 'roadPatrolManagmentMap',
label: 'پراکندگی بر روی نقشه',
type: "page",
route: "./v2/map?type=road_patrols",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_patrols",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'roadPatrolManagmentReport',
label: 'گزارش ها',
type: "page",
route: "./v2/road_patrols/report",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/report",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]
@@ -195,13 +195,13 @@ export const pageMenu = [
id: 'safetyAndPrivacyManagmentOparationCreate',
label: 'ثبت فعالیت',
type: "page",
route: "./safety_and_privacy/operator/first_step",
route: process.env.NEXT_PUBLIC_API_URL + "/safety_and_privacy/operator/first_step",
},
{
id: 'safetyAndPrivacyManagmentOparationCartable',
label: 'کارتابل',
type: "page",
route: "./v2/safety_and_privacy/operator/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/safety_and_privacy/operator/cartable",
},
]
},
@@ -209,14 +209,14 @@ export const pageMenu = [
id: 'safetyAndPrivacyManagmentMap',
label: 'پراکندگی بر روی نقشه',
type: "page",
route: "./v2/map?type=safety_and_privacy",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=safety_and_privacy",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'safetyAndPrivacyManagmentReport',
label: 'گزارش ها',
type: "page",
route: "./v2/safety_and_privacy/report",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/safety_and_privacy/report",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]
@@ -239,7 +239,7 @@ export const pageMenu = [
id: 'roadObservationsManagmentSupervisorCartable',
label: 'کارتابل',
type: "page",
route: "./v2/road_observations/supervisor/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/supervisor/cartable",
},
]
},
@@ -247,7 +247,7 @@ export const pageMenu = [
id: 'roadObservationsManagmentList',
label: 'رسیدگی به شکایات',
type: "page",
route: "./v2/road_observations",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
@@ -261,7 +261,7 @@ export const pageMenu = [
id: 'roadObservationsManagmentOparationCartable',
label: 'کارتابل',
type: "page",
route: "./v2/road_observations/operator/cartable",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/operator/cartable",
},
]
},
@@ -269,14 +269,14 @@ export const pageMenu = [
id: 'roadObservationsManagmentMap',
label: 'پراکندگی بر روی نقشه',
type: "page",
route: "./v2/map?type=road_observations",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_observations",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'roadObservationsManagmentReport',
label: 'گزارش ها',
type: "page",
route: "./v2/road_observations/report/index",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/report/index",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]
@@ -292,21 +292,21 @@ export const pageMenu = [
id: 'winterCampManagmentBlocking',
label: 'محور های انسدادی',
type: "page",
route: "./v2/winter_camp",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/winter_camp",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'winterCampManagmentFirstRing',
label: 'محور های حلقه اول',
type: "page",
route: "./v2/map?type=camp",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=camp",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
{
id: 'winterCampManagmentReport',
label: 'گزارش ها',
type: "page",
route: "./v2/map?type=campNew",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=campNew",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]
@@ -329,7 +329,7 @@ export const pageMenu = [
id: 'receiptManagmentOparationCartable',
label: 'کارتابل',
type: "page",
route: "./v2/receipt",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/receipt",
},
]
},
@@ -337,7 +337,7 @@ export const pageMenu = [
id: 'receiptManagmentReport',
label: 'گزارش ها',
type: "page",
route: "./v2/receipt/report",
route: process.env.NEXT_PUBLIC_API_URL + "/v2/receipt/report",
icon: <Security sx={{ width: 'inherit', height: 'inherit' }} />,
},
]

4
src/core/utils/routes.js Normal file
View File

@@ -0,0 +1,4 @@
const api = process.env.NEXT_PUBLIC_API_URL
export const GET_USER_ROUTE = api + '/webapi/user/get-permission'
export const GET_LOGIN_ROUTE = api + '/test_login'

View File

@@ -0,0 +1,10 @@
'use client'
import { toast } from "react-toastify";
import { successToast } from "@/core/components/toasts/success";
export const successRequest = (notification, toastContainer) => {
if (notification) {
toast.dismiss({ container: toastContainer })
successToast(toastContainer)
}
}

76
src/lib/contexts/auth.js Normal file
View File

@@ -0,0 +1,76 @@
'use client'
import { createContext, useCallback, useContext, useEffect, useReducer } from 'react';
import useRequest from '../hooks/useRequest';
import { GET_USER_ROUTE } from '@/core/utils/routes';
const initAuth = {
initAuthState: false,
isAuth: false,
user: {}
};
const authReducer = (state, action) => {
switch (action.type) {
case "CLEAR_USER":
return { ...state, user: {} };
case "CHANGE_USER":
return { ...state, user: action.user };
case "CHANGE_AUTH_STATE":
return { ...state, isAuth: action.isAuth };
case "CHANGE_INIT_AUTH":
return { ...state, initAuthState: action.initAuthState };
default:
return state;
}
};
const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, initAuth);
const request = useRequest()
const clearUser = useCallback(() => {
dispatch({ type: "CLEAR_USER" });
}, []);
const changeUser = useCallback((user) => {
dispatch({ type: "CHANGE_USER", user });
}, []);
const changeAuthState = useCallback((isAuth) => {
dispatch({ type: "CHANGE_AUTH_STATE", isAuth });
}, []);
const changeInitAuth = useCallback((initAuthState) => {
dispatch({ type: "CHANGE_INIT_AUTH", initAuthState });
}, []);
const getUser = useCallback(async () => {
try {
const { data } = await request(GET_USER_ROUTE, 'get')
changeUser(data);
changeAuthState(true);
changeInitAuth(true);
} catch (error) {
if (error.response && error.response.status === 401) {
clearUser();
changeAuthState(false);
changeInitAuth(true);
}
}
}, [clearUser, changeUser, changeAuthState, changeInitAuth]);
useEffect(() => {
getUser()
}, [])
return <AuthContext.Provider value={{
user: state.user,
isAuth: state.isAuth,
initAuthState: state.initAuthState,
getUser
}}>{children}</AuthContext.Provider>;
};
export const useAuth = () => useContext(AuthContext);

View File

@@ -0,0 +1,42 @@
import { errorResponse } from "@/core/utils/errorResponse";
import { successRequest } from "@/core/utils/successRequest";
import axios from "axios";
const defaultOptions = {
data: {},
requestOptions: {
headers: {}
},
notification: {
show: true,
success: false,
failed: true
},
}
const useRequest = (initOptions) => {
const _options = Object.assign({}, defaultOptions, initOptions);
return async (url = '', method = 'get', options) => {
const mergedOptions = Object.assign({}, _options, options);
try {
const response = await axios({
url,
method,
data: method === 'get' ? null : mergedOptions.data,
withCredentials: true,
...mergedOptions.requestOptions
});
successRequest(mergedOptions.notification.show && mergedOptions.notification.success, 'request_data');
return response;
} catch (error) {
if (error.response) {
errorResponse(error.response, mergedOptions.notification.show && mergedOptions.notification.failed, 'request_data');
}
throw error;
}
}
}
export default useRequest