Return to route after login using navigation instruction

Here is my solution:

  1. I add an Authorization step to the pipeline
  2. The authorization step checks if a login is required and if the user then is logged in
    2.1. The step saves the current url by taking instructions fragment and query
    2.2. A Redirect to the login page is created and returned which aborts the pipeline
  3. If no authorization is required or the user is logged in I check if a origin URL was saved
    3.1. Check If the current instruction fragment is not the login page and I have a origin
    3.2. Create a redirect to the origin and cancel the pipeline
  4. Done

Here’s are the relevant code parts of my AuthorizationStep
import {Redirect} from ‘aurelia-router’;

export class AuthorizationStep {

  static loginFragment = '/login';

  run(instruction, next) {
    return Promise.resolve()
      .then(() => this.checkAuthorization(instruction, next))
      .then(result => result || this.checkOrigin(instruction, next))
      .then(result => result || next());
  }

  checkAuthorization(instruction, next) {
    if (instruction.getAllInstructions().some(i => i.config.auth)) {
      if (!isLoggedIn()) {
        const currentUrl = instruction.fragment + (instruction.queryString ? `?${instruction.queryString}` : '');
        localStorage.setItem('origin', currentUrl);
        return next.cancel(new Redirect(AuthorizationStep.loginFragment));
      }
    }
  }

  checkOrigin(instruction, next) {
    const origin = localStorage.getItem('origin');
    // Check if we were not redirected to login page and have an origin
    if (instruction.fragment !== AuthorizationStep.loginFragment && origin) {
      localStorage.removeItem('origin');
      return next.cancel(new Redirect(origin));
    }
  }
}
4 Likes