master
Tudor Stanciu 2021-07-06 19:26:39 +03:00
parent 0586f20d52
commit fe812a371c
5 changed files with 78 additions and 44 deletions

View File

@ -1,4 +1,4 @@
import React, { Suspense } from "react";
import React, { useEffect } from "react";
import { HashRouter, Route, Switch, Redirect } from "react-router-dom";
// components
@ -10,31 +10,31 @@ import Login from "../pages/login";
// context
import { useUserState } from "../context/UserContext";
import { useTranslation } from "react-i18next";
export default function App() {
// global
var { isAuthenticated } = useUserState();
var { authenticated, messageCode } = useUserState();
const { t } = useTranslation();
useEffect(() => {
if (!messageCode) return;
alert(t(messageCode));
}, [messageCode, t]);
return (
<Suspense fallback={<div>Loading...</div>}>
<HashRouter basename={process.env.PUBLIC_URL || ""}>
<Switch>
<Route
exact
path="/"
render={() => <Redirect to="/app/dashboard" />}
/>
<Route
exact
path="/app"
render={() => <Redirect to="/app/dashboard" />}
/>
<PrivateRoute path="/app" component={Layout} />
<PublicRoute path="/login" component={Login} />
<Route component={Error} />
</Switch>
</HashRouter>
</Suspense>
<HashRouter basename={process.env.PUBLIC_URL || ""}>
<Switch>
<Route exact path="/" render={() => <Redirect to="/app/dashboard" />} />
<Route
exact
path="/app"
render={() => <Redirect to="/app/dashboard" />}
/>
<PrivateRoute path="/app" component={Layout} />
<PublicRoute path="/login" component={Login} />
<Route component={Error} />
</Switch>
</HashRouter>
);
function PrivateRoute({ component, ...rest }) {
@ -42,7 +42,7 @@ export default function App() {
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
authenticated ? (
React.createElement(component, props)
) : (
<Redirect
@ -64,7 +64,7 @@ export default function App() {
<Route
{...rest}
render={(props) =>
isAuthenticated ? (
authenticated ? (
<Redirect
to={{
pathname: "/"

View File

@ -1,4 +1,5 @@
import React from "react";
import { authenticate, invalidate, validateToken } from "../utils/identity";
var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();
@ -6,9 +7,15 @@ var UserDispatchContext = React.createContext();
function userReducer(state, action) {
switch (action.type) {
case "LOGIN_SUCCESS":
return { ...state, isAuthenticated: true };
return { ...state, authenticated: true };
case "SIGN_OUT_SUCCESS":
return { ...state, isAuthenticated: false };
return { ...state, authenticated: false };
case "LOGIN_FAILURE":
return {
...state,
authenticated: false,
messageCode: action.payload?.messageCode
};
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
@ -17,7 +24,7 @@ function userReducer(state, action) {
function UserProvider({ children }) {
var [state, dispatch] = React.useReducer(userReducer, {
isAuthenticated: !!localStorage.getItem("id_token"),
authenticated: validateToken() === true
});
return (
@ -45,32 +52,42 @@ function useUserDispatch() {
return context;
}
export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };
// ###########################################################
function setLoginFailed(dispatch, setError, setIsLoading, messageCode) {
dispatch({ type: "LOGIN_FAILURE", payload: { messageCode } });
setError(true);
setIsLoading(false);
}
function loginUser(dispatch, login, password, history, setIsLoading, setError) {
setError(false);
setIsLoading(true);
if (!!login && !!password) {
setTimeout(() => {
localStorage.setItem('id_token', 1)
setError(null)
setIsLoading(false)
dispatch({ type: 'LOGIN_SUCCESS' })
authenticate(login, password).then((response) => {
if (response.status === "SUCCESS") {
setError(null);
setIsLoading(false);
dispatch({ type: "LOGIN_SUCCESS", payload: { token: response.token } });
} else if (response.status === "BAD_CREDENTIALS") {
setLoginFailed(
dispatch,
setError,
setIsLoading,
"Login.IncorrectCredentials"
);
}
});
history.push('/app/dashboard')
}, 2000);
history.push("/app/dashboard");
} else {
dispatch({ type: "LOGIN_FAILURE" });
setError(true);
setIsLoading(false);
setLoginFailed(dispatch, setError, setIsLoading, "Login.EmptyCredentials");
}
}
function signOut(dispatch, history) {
localStorage.removeItem("id_token");
invalidate();
dispatch({ type: "SIGN_OUT_SUCCESS" });
history.push("/login");
}
export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

1
src/hooks/index.js Normal file
View File

@ -0,0 +1 @@
//export { useAuthorizationToken } from "./useAuthorizationToken";

View File

@ -1,4 +1,4 @@
import React from "react";
import React, { Suspense } from "react";
import ReactDOM from "react-dom";
import { ThemeProvider } from "@material-ui/styles";
import { CssBaseline } from "@material-ui/core";
@ -14,7 +14,9 @@ ReactDOM.render(
<UserProvider>
<ThemeProvider theme={Themes.default}>
<CssBaseline />
<App />
<Suspense fallback={<div>Loading...</div>}>
<App />
</Suspense>
</ThemeProvider>
</UserProvider>
</LayoutProvider>,

View File

@ -32,4 +32,18 @@ const invalidate = () => {
}
};
export { storageKeys, authenticate, invalidate };
const validateToken = () => {
const token = getItem(storageKeys.TOKEN);
if (!token) {
return false;
}
const valid = new Date(token.validUntil) >= new Date();
if (!valid) {
invalidate();
}
return valid;
};
export { storageKeys, authenticate, invalidate, validateToken };