Josh Graham
Josh Graham

Reputation: 1208

How to show an unauthorized view at the requested URL in Aurelia

If inside of an Aurelia canActivate method, it is determined the user should not be able to view the requested page. How do I show an "Unauthorized" page to that user, at the URL they are not allowed to reach?

I do not want to return a new Redirect("#/unauthorized") because then the user can't see which URL they are not allowed to visit and I have some navigation bar state in the URL that would be lost.

Note: A possible answer might be, "You are doing this all wrong". :)

Upvotes: 2

Views: 276

Answers (1)

Dwayne Charrington
Dwayne Charrington

Reputation: 6622

You want to show an unauthorized page without the URL changing. So if the user visits "/restricted-page" and they're not allowed to see it, show an unauthorized template instead of the actual page.

To accomplish that, you can set a template value on the ViewModel itself from within the canActivate method if the user doesn't pass the appropriate checks. Then within the getViewStrategy on your ViewModel you will check if this value has been set and display that View or if not, then display your regular View.

export class ViewModel {
  viewTemplate = "./view-model.html";

  canActivate(params, routeConfig) {
    if (!canViewPage) {
      this.viewTemplate = "./401-unauthorized.html";
    }
  }

  getViewStrategy() {
    return this.viewTemplate;
  }  
}

To simplify this further you can just set the getViewStrategy function itself from inside of canActivate.

export class ViewModel {
  canActivate(params, routeConfig) {
    if (!canViewPage) {
      this.getViewStrategy = function() { return "./401-unauthorized.html"; };
    }
  }
}

Upvotes: 1

Related Questions