2022-07-22 11:05:20 -04:00
|
|
|
import React, { Fragment } from 'react'
|
2021-02-08 11:03:30 -05:00
|
|
|
import { Route, RouteProps, Redirect } from 'react-router-dom';
|
2022-07-22 11:05:20 -04:00
|
|
|
import { SpinnerIcon } from './components/icons';
|
2021-02-08 11:03:30 -05:00
|
|
|
|
|
|
|
import { useAuth } from './auth-context';
|
|
|
|
|
|
|
|
export const PrivateRoute: React.FC<RouteProps> = ({component: Component, children, ...rest}) => {
|
2022-07-22 11:05:20 -04:00
|
|
|
const { isAuthenticated, isLoading } = useAuth();
|
2021-02-08 11:03:30 -05:00
|
|
|
|
|
|
|
return <Route
|
|
|
|
{...rest}
|
|
|
|
render={props => {
|
|
|
|
if(isAuthenticated) {
|
|
|
|
if(Component) {
|
|
|
|
return <Component {...props} />;
|
|
|
|
} else if(children) {
|
|
|
|
return <>{children}</>;
|
|
|
|
}
|
2022-07-22 11:05:20 -04:00
|
|
|
|
2021-02-08 11:03:30 -05:00
|
|
|
} else {
|
2022-07-22 11:05:20 -04:00
|
|
|
if (isLoading) {
|
|
|
|
return <Fragment><SpinnerIcon spin={true} /> Loading user info...</Fragment>
|
|
|
|
}
|
2021-02-08 11:03:30 -05:00
|
|
|
return <Redirect to={{
|
|
|
|
pathname: "/login.html",
|
|
|
|
state: { from: props.location.pathname }
|
|
|
|
}} />;
|
|
|
|
}
|
2022-07-22 11:05:20 -04:00
|
|
|
}}
|
2021-02-08 11:03:30 -05:00
|
|
|
/>
|
|
|
|
};
|
|
|
|
|
|
|
|
export const AuthRoute: React.FC<RouteProps> = ({ component: Component, children, ...rest}) => {
|
|
|
|
const { isAuthenticated } = useAuth();
|
|
|
|
|
|
|
|
return <Route
|
|
|
|
{...rest}
|
|
|
|
render={props => {
|
|
|
|
if(isAuthenticated) {
|
2022-02-02 10:06:57 -05:00
|
|
|
let state = props.location.state as any;
|
|
|
|
let from = '/my-account.html';
|
2022-07-22 10:52:16 -04:00
|
|
|
if (typeof state == 'object' && 'from' in state){
|
2022-02-02 10:06:57 -05:00
|
|
|
from = state.from;
|
|
|
|
}
|
|
|
|
|
2021-02-08 11:03:30 -05:00
|
|
|
return <Redirect to={{pathname: from }} />;
|
|
|
|
} else {
|
|
|
|
if(Component) {
|
|
|
|
return <Component {...props} />;
|
|
|
|
} else if(children) {
|
|
|
|
return <>{children}</>;
|
|
|
|
}
|
|
|
|
}
|
2022-07-22 11:05:20 -04:00
|
|
|
}}
|
2021-02-08 11:03:30 -05:00
|
|
|
/>
|
|
|
|
};
|