Replacing localStorage with token in Routes
This commit is contained in:
parent
151e8a8366
commit
83f8f9de61
120
src/index.tsx
120
src/index.tsx
@ -1,9 +1,9 @@
|
|||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import CssBaseline from "@mui/material/CssBaseline";
|
import CssBaseline from "@mui/material/CssBaseline";
|
||||||
import { SnackbarProvider } from 'notistack';
|
import { SnackbarProvider } from "notistack";
|
||||||
import { ThemeProvider } from '@mui/material/styles';
|
import { ThemeProvider } from "@mui/material/styles";
|
||||||
import { createRoot } from 'react-dom/client';
|
import { createRoot } from "react-dom/client";
|
||||||
import { BrowserRouter, Routes, Route, Outlet, Navigate } from "react-router-dom";
|
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||||
import theme from "./theme";
|
import theme from "./theme";
|
||||||
import PublicRoute from "@kitUI/publicRoute";
|
import PublicRoute from "@kitUI/publicRoute";
|
||||||
import PrivateRoute from "@kitUI/privateRoute";
|
import PrivateRoute from "@kitUI/privateRoute";
|
||||||
@ -21,44 +21,82 @@ import PromocodeManagement from "@pages/dashboard/Content/PromocodeManagement";
|
|||||||
import Support from "@root/pages/dashboard/Content/Support/Support";
|
import Support from "@root/pages/dashboard/Content/Support/Support";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
|
|
||||||
const componentsArray = [
|
const componentsArray = [
|
||||||
["/users", <Users />],
|
["/users", <Users />],
|
||||||
["/entities",<Entities />],
|
["/entities", <Entities />],
|
||||||
["/tariffs", <Tariffs />],
|
["/tariffs", <Tariffs />],
|
||||||
["/discounts", <DiscountManagement />],
|
["/discounts", <DiscountManagement />],
|
||||||
["/promocode", <PromocodeManagement />],
|
["/promocode", <PromocodeManagement />],
|
||||||
["/support", <Support />],
|
["/support", <Support />],
|
||||||
["/support/:ticketId", <Support />],
|
["/support/:ticketId", <Support />],
|
||||||
]
|
];
|
||||||
|
|
||||||
const container = document.getElementById('root');
|
const container = document.getElementById("root");
|
||||||
const root = createRoot(container!);
|
const root = createRoot(container!);
|
||||||
root.render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<CssBaseline />
|
|
||||||
<ThemeProvider theme={theme}>
|
|
||||||
<SnackbarProvider>
|
|
||||||
<BrowserRouter>
|
|
||||||
<Routes>
|
|
||||||
<Route path="/" element={<PublicRoute><Signin /></PublicRoute> } />
|
|
||||||
<Route path="/signin" element={ <PublicRoute><Signin /></PublicRoute> } />
|
|
||||||
<Route path="/signup" element={ <PublicRoute><Signup /></PublicRoute> } />
|
|
||||||
<Route path="/restore" element={ <PublicRoute><Restore /></PublicRoute> } />
|
|
||||||
<Route path="/dispatch" element={ <PublicRoute><Sections /></PublicRoute> } />
|
|
||||||
<Route element={<PrivateRoute><Dashboard/></PrivateRoute>}>
|
|
||||||
{componentsArray.map((e:any, i) => (
|
|
||||||
<Route key={i} path={e[0]} element={e[1]} />
|
|
||||||
))}
|
|
||||||
</Route>
|
|
||||||
|
|
||||||
<Route
|
root.render(
|
||||||
path="*"
|
<React.StrictMode>
|
||||||
element={ <Error404 /> }
|
<CssBaseline />
|
||||||
/>
|
<ThemeProvider theme={theme}>
|
||||||
</Routes>
|
<SnackbarProvider>
|
||||||
</BrowserRouter>
|
<BrowserRouter>
|
||||||
</SnackbarProvider>
|
<Routes>
|
||||||
</ThemeProvider>
|
<Route
|
||||||
</React.StrictMode>
|
path="/"
|
||||||
);
|
element={
|
||||||
|
<PublicRoute>
|
||||||
|
<Signin />
|
||||||
|
</PublicRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/signin"
|
||||||
|
element={
|
||||||
|
<PublicRoute>
|
||||||
|
<Signin />
|
||||||
|
</PublicRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/signup"
|
||||||
|
element={
|
||||||
|
<PublicRoute>
|
||||||
|
<Signup />
|
||||||
|
</PublicRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/restore"
|
||||||
|
element={
|
||||||
|
<PublicRoute>
|
||||||
|
<Restore />
|
||||||
|
</PublicRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
path="/dispatch"
|
||||||
|
element={
|
||||||
|
<PublicRoute>
|
||||||
|
<Sections />
|
||||||
|
</PublicRoute>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Route
|
||||||
|
element={
|
||||||
|
<PrivateRoute>
|
||||||
|
<Dashboard />
|
||||||
|
</PrivateRoute>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{componentsArray.map((e: any, i) => (
|
||||||
|
<Route key={i} path={e[0]} element={e[1]} />
|
||||||
|
))}
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
<Route path="*" element={<Error404 />} />
|
||||||
|
</Routes>
|
||||||
|
</BrowserRouter>
|
||||||
|
</SnackbarProvider>
|
||||||
|
</ThemeProvider>
|
||||||
|
</React.StrictMode>
|
||||||
|
);
|
||||||
|
@ -1,12 +1,13 @@
|
|||||||
|
import { authStore } from "@root/stores/auth";
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { useLocation, Navigate } from 'react-router-dom'
|
import { useLocation, Navigate } from "react-router-dom";
|
||||||
|
|
||||||
export default ({ children }: any) => {
|
export default ({ children }: any) => {
|
||||||
const location = useLocation()
|
const { token } = authStore();
|
||||||
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
const location = useLocation();
|
||||||
if (localStorage.getItem('AT')) {
|
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
||||||
return children
|
if (token) {
|
||||||
}
|
return children;
|
||||||
return <Navigate to="/" state={{from: location}} />
|
}
|
||||||
|
return <Navigate to="/" state={{ from: location }} />;
|
||||||
}
|
};
|
||||||
|
@ -1,12 +1,16 @@
|
|||||||
import * as React from "react";
|
import { useLocation, Navigate } from "react-router-dom";
|
||||||
import { useLocation, Navigate } from 'react-router-dom'
|
|
||||||
|
|
||||||
export default ({ children }: any) => {
|
import { authStore } from "@root/stores/auth";
|
||||||
const location = useLocation()
|
|
||||||
//Если пользователь авторизован, перенаправляем его в приложение. Иначе пускаем куда хотел
|
|
||||||
if (localStorage.getItem('AT')) {
|
|
||||||
return <Navigate to="/users" state={{from: location}} />
|
|
||||||
}
|
|
||||||
return children
|
|
||||||
|
|
||||||
}
|
const PublicRoute = ({ children }: any) => {
|
||||||
|
const location = useLocation();
|
||||||
|
const { token } = authStore();
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
return <Navigate to="/users" state={{ from: location }} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return children;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PublicRoute;
|
||||||
|
@ -19,48 +19,55 @@ interface Values {
|
|||||||
|
|
||||||
function validate(values: Values) {
|
function validate(values: Values) {
|
||||||
const errors = {} as any;
|
const errors = {} as any;
|
||||||
|
|
||||||
if (!values.email) {
|
if (!values.email) {
|
||||||
errors.email = "Required";
|
errors.email = "Required";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!values.password) {
|
if (!values.password) {
|
||||||
errors.password = "Required";
|
errors.password = "Required";
|
||||||
} else if (!/^[\S]{8,25}$/i.test(values.password)) {
|
}
|
||||||
|
|
||||||
|
if (values.password && !/^[\S]{8,25}$/i.test(values.password)) {
|
||||||
errors.password = "Invalid password";
|
errors.password = "Invalid password";
|
||||||
}
|
}
|
||||||
|
|
||||||
return errors;
|
return errors;
|
||||||
}
|
}
|
||||||
export default () => {
|
|
||||||
|
const SigninForm = () => {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [isReady, setIsReady] = React.useState(true);
|
const [isReady] = React.useState(true);
|
||||||
|
|
||||||
const { makeRequest } = authStore();
|
const { makeRequest } = authStore();
|
||||||
|
|
||||||
|
const initialValues: Values = {
|
||||||
|
email: "",
|
||||||
|
password: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const onSignFormSubmit = (values: Values) => {
|
||||||
|
makeRequest({
|
||||||
|
url: "https://admin.pena.digital/auth/login",
|
||||||
|
body: {
|
||||||
|
email: values.email,
|
||||||
|
password: values.password,
|
||||||
|
},
|
||||||
|
useToken: false,
|
||||||
|
})
|
||||||
|
.then((e) => {
|
||||||
|
console.log(e);
|
||||||
|
navigate("/users");
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.log(e);
|
||||||
|
enqueueSnackbar(e.message ? e.message : `Unknown error`);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Formik
|
<Formik initialValues={initialValues} validate={validate} onSubmit={onSignFormSubmit}>
|
||||||
initialValues={{
|
|
||||||
email: "",
|
|
||||||
password: "",
|
|
||||||
}}
|
|
||||||
validate={validate}
|
|
||||||
onSubmit={(values) => {
|
|
||||||
makeRequest({
|
|
||||||
url: "https://admin.pena.digital/auth/login",
|
|
||||||
body: {
|
|
||||||
email: values.email,
|
|
||||||
password: values.password,
|
|
||||||
},
|
|
||||||
useToken: false,
|
|
||||||
})
|
|
||||||
.then((e) => {
|
|
||||||
console.log(e);
|
|
||||||
navigate("/users");
|
|
||||||
})
|
|
||||||
.catch((e) => {
|
|
||||||
console.log(e);
|
|
||||||
enqueueSnackbar(e.message ? e.message : `Unknown error`);
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Form>
|
<Form>
|
||||||
<Box
|
<Box
|
||||||
component="section"
|
component="section"
|
||||||
@ -153,3 +160,5 @@ export default () => {
|
|||||||
</Formik>
|
</Formik>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export default SigninForm;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import axios, { AxiosResponse } from "axios";
|
import axios, { AxiosError, AxiosResponse } from "axios";
|
||||||
import { create } from "zustand";
|
import { create } from "zustand";
|
||||||
import { devtools } from "zustand/middleware";
|
import { devtools } from "zustand/middleware";
|
||||||
|
|
||||||
@ -60,7 +60,7 @@ async function makeRequest<TRequest, TResponse>({
|
|||||||
if (contentType) headers["Content-Type"] = "application/json";
|
if (contentType) headers["Content-Type"] = "application/json";
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axios<TRequest, AxiosResponse<TResponse & { accessToken?: string }>>({
|
const { data } = await axios<TRequest, AxiosResponse<TResponse & { accessToken?: string }>>({
|
||||||
url,
|
url,
|
||||||
method,
|
method,
|
||||||
headers,
|
headers,
|
||||||
@ -68,12 +68,14 @@ async function makeRequest<TRequest, TResponse>({
|
|||||||
signal,
|
signal,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.data?.accessToken) {
|
if (data?.accessToken) {
|
||||||
HC(response.data.accessToken);
|
HC(data.accessToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
return response.data;
|
return data;
|
||||||
} catch (error: any) {
|
} catch (nativeError: unknown) {
|
||||||
|
const error = nativeError as AxiosError;
|
||||||
|
|
||||||
if (error?.response?.status === 401 && counterRefresh) {
|
if (error?.response?.status === 401 && counterRefresh) {
|
||||||
const refreshResponse = await refresh();
|
const refreshResponse = await refresh();
|
||||||
if (refreshResponse.data?.accessToken) HC(refreshResponse.data.accessToken);
|
if (refreshResponse.data?.accessToken) HC(refreshResponse.data.accessToken);
|
||||||
|
Loading…
Reference in New Issue
Block a user