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 CssBaseline from "@mui/material/CssBaseline";
|
||||
import { SnackbarProvider } from 'notistack';
|
||||
import { ThemeProvider } from '@mui/material/styles';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter, Routes, Route, Outlet, Navigate } from "react-router-dom";
|
||||
import { SnackbarProvider } from "notistack";
|
||||
import { ThemeProvider } from "@mui/material/styles";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import theme from "./theme";
|
||||
import PublicRoute from "@kitUI/publicRoute";
|
||||
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 "./index.css";
|
||||
|
||||
|
||||
const componentsArray = [
|
||||
["/users", <Users />],
|
||||
["/entities",<Entities />],
|
||||
["/tariffs", <Tariffs />],
|
||||
["/discounts", <DiscountManagement />],
|
||||
["/promocode", <PromocodeManagement />],
|
||||
["/support", <Support />],
|
||||
["/support/:ticketId", <Support />],
|
||||
]
|
||||
["/users", <Users />],
|
||||
["/entities", <Entities />],
|
||||
["/tariffs", <Tariffs />],
|
||||
["/discounts", <DiscountManagement />],
|
||||
["/promocode", <PromocodeManagement />],
|
||||
["/support", <Support />],
|
||||
["/support/:ticketId", <Support />],
|
||||
];
|
||||
|
||||
const container = document.getElementById('root');
|
||||
const container = document.getElementById("root");
|
||||
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
|
||||
path="*"
|
||||
element={ <Error404 /> }
|
||||
/>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</SnackbarProvider>
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>
|
||||
);
|
||||
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 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 { useLocation, Navigate } from 'react-router-dom'
|
||||
import { useLocation, Navigate } from "react-router-dom";
|
||||
|
||||
export default ({ children }: any) => {
|
||||
const location = useLocation()
|
||||
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
||||
if (localStorage.getItem('AT')) {
|
||||
return children
|
||||
}
|
||||
return <Navigate to="/" state={{from: location}} />
|
||||
|
||||
}
|
||||
const { token } = authStore();
|
||||
const location = useLocation();
|
||||
//Если пользователь авторизован, перенаправляем его на нужный путь. Иначе выкидываем в регистрацию
|
||||
if (token) {
|
||||
return children;
|
||||
}
|
||||
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) => {
|
||||
const location = useLocation()
|
||||
//Если пользователь авторизован, перенаправляем его в приложение. Иначе пускаем куда хотел
|
||||
if (localStorage.getItem('AT')) {
|
||||
return <Navigate to="/users" state={{from: location}} />
|
||||
}
|
||||
return children
|
||||
import { authStore } from "@root/stores/auth";
|
||||
|
||||
}
|
||||
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) {
|
||||
const errors = {} as any;
|
||||
|
||||
if (!values.email) {
|
||||
errors.email = "Required";
|
||||
}
|
||||
|
||||
if (!values.password) {
|
||||
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";
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
export default () => {
|
||||
|
||||
const SigninForm = () => {
|
||||
const theme = useTheme();
|
||||
const navigate = useNavigate();
|
||||
const [isReady, setIsReady] = React.useState(true);
|
||||
const [isReady] = React.useState(true);
|
||||
|
||||
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 (
|
||||
<Formik
|
||||
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`);
|
||||
});
|
||||
}}
|
||||
>
|
||||
<Formik initialValues={initialValues} validate={validate} onSubmit={onSignFormSubmit}>
|
||||
<Form>
|
||||
<Box
|
||||
component="section"
|
||||
@ -153,3 +160,5 @@ export default () => {
|
||||
</Formik>
|
||||
);
|
||||
};
|
||||
|
||||
export default SigninForm;
|
||||
|
@ -1,4 +1,4 @@
|
||||
import axios, { AxiosResponse } from "axios";
|
||||
import axios, { AxiosError, AxiosResponse } from "axios";
|
||||
import { create } from "zustand";
|
||||
import { devtools } from "zustand/middleware";
|
||||
|
||||
@ -60,7 +60,7 @@ async function makeRequest<TRequest, TResponse>({
|
||||
if (contentType) headers["Content-Type"] = "application/json";
|
||||
|
||||
try {
|
||||
const response = await axios<TRequest, AxiosResponse<TResponse & { accessToken?: string }>>({
|
||||
const { data } = await axios<TRequest, AxiosResponse<TResponse & { accessToken?: string }>>({
|
||||
url,
|
||||
method,
|
||||
headers,
|
||||
@ -68,12 +68,14 @@ async function makeRequest<TRequest, TResponse>({
|
||||
signal,
|
||||
});
|
||||
|
||||
if (response.data?.accessToken) {
|
||||
HC(response.data.accessToken);
|
||||
if (data?.accessToken) {
|
||||
HC(data.accessToken);
|
||||
}
|
||||
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
return data;
|
||||
} catch (nativeError: unknown) {
|
||||
const error = nativeError as AxiosError;
|
||||
|
||||
if (error?.response?.status === 401 && counterRefresh) {
|
||||
const refreshResponse = await refresh();
|
||||
if (refreshResponse.data?.accessToken) HC(refreshResponse.data.accessToken);
|
||||
|
Loading…
Reference in New Issue
Block a user