Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // App
- class App extends Component {
- render() {
- //...
- return (
- <Fragment>
- <NotificationContainer />
- <IntlProvider
- locale={currentAppLocale.locale}
- messages={currentAppLocale.messages}
- >
- <Fragment>
- <Switch>
- {/* First protected route */}
- <Route path={`${match.url}app`} component={MainProtectedRoute} />
- {/* --------------------------------------------------------- */}
- {/* Below are all unprotected routes */}
- {/* --------------------------------------------------------- */}
- {/* Error page, unprotected route. */}
- <Route path={`/error`} component={error} />
- {/* Callback for Auth0 */}
- <Route
- path="/callback"
- render={props => {
- handleAuthentication(this.props);
- return <Callback {...props} />;
- }}
- />
- <Redirect to="/error" />
- </Switch>
- </Fragment>
- </IntlProvider>
- </Fragment>
- );
- }
- }
- // MainProtectedRoute
- class MainApp extends Component {
- constructor(props) {
- super(props);
- }
- async componentDidMount() {
- //======================================
- //========== Authentication ============
- //======================================
- // Auth checking
- await renewSession(this.props.dispatch);
- }
- render() {
- const { match, containerClassnames } = this.props;
- if (this.props.auth.user === false) {
- return (
- <div className="custom-spinner" >
- <div className="loading"></div>
- </div>
- );
- } else {
- // Here I check first allowed route for the user based on it permissions and redirect it there.
- // ...
- return (
- <div id="app-container" className={containerClassnames}>
- <TopNav history={this.props.history} />
- <Sidebar />
- <main>
- <div className="container-fluid">
- <Switch>
- <Route path={`${match.url}/some1`} component={some1} />
- //...
- <Redirect to="/error" />
- </Switch>
- <ColorSwitcher />
- </div>
- </main>
- </div>
- );
- };
- }
- }
- const mapStateToProps = (state) => {
- const { containerClassnames } = state.menu;
- return {
- containerClassnames,
- auth: state.auth,
- loading: state.loading.loading
- }
- };
- export default withRouter(
- connect(
- mapStateToProps,
- )(MainApp)
- );
- // renewSession
- /**
- * Check if session is still active, renewal user's data from access_token
- */
- export const renewSession = (dispatch = false) => {
- // https://auth0.com/docs/api-auth/tutorials/silent-authentication#renew-expired-tokens
- _auth0connection.checkSession({}, (err, authResult) => {
- if (authResult && authResult.accessToken && authResult.idToken) {
- // User still authenticated, as payload on Auth0 may be changed in real time, I rewrite payload data on each checking of auth
- // to be able to react payload changes on the fly.
- _setSession(authResult, dispatch);
- } else if (err) {
- // Needs to be authenticated
- login();
- }
- });
- }
- // Below are helper functions for renewSession
- const _auth0connection = new auth0.WebAuth({
- domain: AUTH_CONFIG.domain,
- clientID: AUTH_CONFIG.clientID,
- redirectUri: AUTH_CONFIG.callbackUrl,
- responseType: '...',
- audience: `...`,
- scope: '...'
- });
- const _setSession = (authResult, dispatch, permissions = false) => {
- _setToState(authResult, dispatch);
- _scheduleRenewal(authResult.idTokenPayload.exp, dispatch);
- }
- import jwt_decode from 'jwt-decode';
- const _setToState = (authResult, dispatch) => {
- const authInfo = {
- clientId: authResult.idTokenPayload.sub,
- expiresAt: authResult.expiresAt,
- accessToken: authResult.accessToken,
- state: authResult.state,
- idTokenPayload: {
- //...
- },
- permissions: jwt_decode(authResult.accessToken).permissions
- };
- dispatch(setAuthStore(authInfo));
- }
- // setAuthStore at the end does (stores data from access_token to redux store):
- case SET_AUTH_STORE:
- return {
- ...state,
- user: action.payload
- }
- break;
- const _scheduleRenewal = (exp, dispatch) => {
- let expiresAt = exp;
- const timeout = expiresAt * 1000 - Date.now();
- if (timeout > 1) {
- const tokenRenewalTimeout = setTimeout(() => {
- renewSession(dispatch);
- }, timeout);
- dispatch(setAuthTimer(tokenRenewalTimeout));
- }
- }
- // setAuthTime does:
- case SET_AUTH_TIMER:
- return {
- ...state,
- tokenRenewalTimeout: action.payload
- }
- export const login = () => {
- _auth0connection.authorize();
- }
Add Comment
Please, Sign In to add comment