Aurelia Router: Good pattern for authorizing child routes

时间:2018-03-22 23:23:46

标签: aurelia aurelia-router

I'd like to authorize routes on a child router, but I'm not super happy with the current solution that I have. My current routes look like the following:

/
/account
/account/signin
/account/signout

To implement this, I've defined two routers - a root router and a child router for the account pages. To authorize the routes on my account child router, I added the following pipeline step to my root router config.

config.addAuthorizeStep({
    run: (instruction: NavigationInstruction, next: Next): Promise<any> => {
        if (!this.auth.isAuthenticated && (instruction.fragment === '/account' || instruction.fragment === '/account/profile')) {
            return next.cancel(new Redirect('account/signin'))
        }

        if (this.auth.isAuthenticated && instruction.fragment === '/account/signin') {
            return next.cancel(new Redirect('account'))
        }

        if (this.auth.isAuthenticated && instruction.fragment === '/account/signup') {
            return next.cancel(new Redirect('account'))
        }

        return next();
    }
})

It works, but I feel like there has to be a better way... I'd really like to accomplish the following:

  1. Move the authorize logic to the account child router.
  2. Use route names instead of fragments as it seems more robust

1 个答案:

答案 0 :(得分:1)

您可以添加auth属性以路由配置并检查该配置

http://aurelia.io/docs/routing/configuration#pipelines

import {Redirect} from 'aurelia-router';

export class App {
  configureRouter(config) {
    config.addAuthorizeStep(AuthorizeStep);
    config.map([
      { route: ['', 'home'],       name: 'home',       moduleId: 'home/index' },
      { route: 'users',            name: 'users',      moduleId: 'users/index',  settings: { auth: true } },
      { route: 'users/:id/detail', name: 'userDetail', moduleId: 'users/detail', settings: { auth: true } }
    ]);
  }
}

class AuthorizeStep {
  run(navigationInstruction, next) {
    if (navigationInstruction.getAllInstructions().some(i => i.config.settings.auth)) {
      var isLoggedIn = // insert magic here;
      if (!isLoggedIn) {
        return next.cancel(new Redirect('login'));
      }
    }

    return next();
  }
}