Trouble with refreshing the page after token expired


#1

I have a boot.ts file that controls the start of Aurelia via as well as any page refreshes using a function - configure.

    import "isomorphic-fetch";
    import { Aurelia, PLATFORM } from "aurelia-framework";
    import { HttpClient } from "aurelia-fetch-client";
    import "bootstrap/dist/css/bootstrap.css";
    import "bootstrap";
    declare const IS_DEV_BUILD: boolean; // The value is supplied by Webpack during the build
    import { AuthService } from "./services/auth/auth-service"

    export function configure(aurelia: Aurelia) {
        aurelia.use
            .standardConfiguration()
            .plugin(PLATFORM.moduleName("aurelia-validation"));

        if (IS_DEV_BUILD) {
            aurelia.use.developmentLogging();
        }

        new HttpClient().configure(config => {
            const baseUrl = document.getElementsByTagName("base")[0].href;
            config.withBaseUrl(baseUrl);
        });

        // After starting the aurelia, we can request the AuthService directly
        // from the DI container on the aurelia object. We can then set the 
        // correct root by querying the AuthService's checkJWTStatus() method
        // to determine if the JWT exists and is valid.
        aurelia.start().then(() => {
            var auth = aurelia.container.get(AuthService);

            console.log("BOOT!");
            let root: string = auth.checkJWTStatus() ? PLATFORM.moduleName('app/app/app') : PLATFORM.moduleName('public/public/public');
            aurelia.setRoot(root, document.body)
        });

    }

The function “checkJWTStatus()” is simple and just checks if the token exists and if it is valid.

  checkJWTStatus(): string {
      const session = localStorage.getItem(this.TOKEN_KEY);
      if (!session) {
            return false;
      }
      if (this.hasTokenExpired()) {
            return false;
      }
        return true;
  }

If I refresh the page when the token exists but has expired it goes to the public root.

The problem is, it retains the old page route for the new root. It does not start fresh. Consequently it tries to go to non existent page in the public root and ends up showing “page not found” from the mapUnknownRoutes("not found") option on the public root.

I had the idea of using router.navigate.reset()) but the boot.ts file does not have the current instance of router. I would like to be sent to the login page in the public root but I have no idea how to do that in boot.ts.

I would normally use this.router.navigate('login') but I dont have access to router…

How do I force the application to navigate to the route “login”?

Is it possible to get access to router after moving to the public root and then do the navigate in the boot.ts file?

Assistance would be greatly appreciated…


#2

Check your token in canActivate hook and return redirect to a proper page.