accounts-frontend/packages/app/containers/AuthFlowRouteContents.tsx

98 lines
2.0 KiB
TypeScript
Raw Normal View History

2019-12-07 13:28:52 +02:00
import React from 'react';
2019-12-10 09:47:32 +02:00
import { Redirect, RouteComponentProps } from 'react-router-dom';
import authFlow from 'app/services/authFlow';
2019-12-10 09:47:32 +02:00
interface Props {
component:
| React.ComponentType<RouteComponentProps<any>>
| React.ComponentType<any>;
routerProps: RouteComponentProps;
}
interface State {
access: null | 'rejected' | 'allowed';
component: React.ReactElement | null;
}
2019-12-07 13:28:52 +02:00
export default class AuthFlowRouteContents extends React.Component<
2019-12-10 09:47:32 +02:00
Props,
State
> {
2019-12-10 09:47:32 +02:00
state: State = {
access: null,
component: null,
};
2019-12-10 09:47:32 +02:00
mounted = false;
shouldComponentUpdate(
{ routerProps: nextRoute, component: nextComponent }: Props,
state: State,
) {
const { component: prevComponent, routerProps: prevRoute } = this.props;
return (
prevRoute.location.pathname !== nextRoute.location.pathname ||
prevRoute.location.search !== nextRoute.location.search ||
prevComponent !== nextComponent ||
this.state.access !== state.access
);
}
componentDidMount() {
2019-12-10 09:47:32 +02:00
this.mounted = true;
this.handleProps(this.props);
}
2019-12-10 09:47:32 +02:00
componentDidUpdate() {
this.handleProps(this.props);
}
componentWillUnmount() {
2019-12-10 09:47:32 +02:00
this.mounted = false;
}
render() {
return this.state.component;
}
2019-12-10 09:47:32 +02:00
handleProps(props: Props) {
const { routerProps } = props;
authFlow.handleRequest(
{
path: routerProps.location.pathname,
params: routerProps.match.params,
2019-12-10 09:47:32 +02:00
query: new URLSearchParams(routerProps.location.search),
},
this.onRedirect.bind(this),
this.onRouteAllowed.bind(this, props),
);
}
onRedirect(path: string) {
2019-12-10 09:47:32 +02:00
if (!this.mounted) {
return;
}
this.setState({
2019-12-10 09:47:32 +02:00
access: 'rejected',
component: <Redirect to={path} />,
});
}
2019-12-10 09:47:32 +02:00
onRouteAllowed(props: Props) {
if (!this.mounted) {
return;
}
2019-12-10 09:47:32 +02:00
const { component: Component } = props;
this.setState({
2019-12-10 09:47:32 +02:00
access: 'allowed',
component: <Component {...props.routerProps} />,
});
}
}