使用 Aurelia 的 Firebase 角色授权

Firebase Role Authorization with Aurelia

目前为了避免未登录的用户在未经许可的情况下进入任何路由,我设置了这个class:

export class AuthorizeStep {
  run(navigationInstruction, next) {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged(user => {
        let currentRoute = navigationInstruction.config;
        let loginRequired = currentRoute.auth && currentRoute.auth === true;

        if (!user && loginRequired) {
          return resolve(next.cancel(new Redirect('')));
        }

        return resolve(next());
      });
    });
  }

这里调用的是:

configureRouter(config, router) {
    this.router = router;
    config.title = 'title';

    config.map([
      { route: ['', 'inicio'], name: 'inicio', moduleId: './modules/contacts/components/inicio', title: 'au-samples.contacts.mainPage' },
      { route: 'conta', name: 'conta', moduleId: './modules/admin/conta', title: 'accountMessages.account', auth: true},
      { route: 'contacts', name: 'contacts', moduleId: './modules/contacts/components/list', title: 'au-samples.contacts.contacts', auth: true},
      { route: ':id', name: 'contact-details', moduleId: './modules/contacts/components/details', auth: true },
      { route: ':id/edit', name: 'contact-edition', moduleId: './modules/contacts/components/edition', auth: true },
      { route: ':id/photo', name: 'contact-photo', moduleId: './modules/contacts/components/photo', auth: true }
    ]);
    config.mapUnknownRoutes('not-found');
    config.addPipelineStep('authorize', AuthorizeStep);
  }

所有这些都运行良好,但我希望有一种方法可以让我提取用户的数据,我有办法做到这一点,发挥它的作用(我也可以做到)并在访问特定路由之前检查用户是否具有该角色,我想知道我是否需要做另一个 class 并在我的 configureRouter 中使用 addPipelineStep 调用它,或者启用角色的另一种方法是什么- 基于变量的授权(在本例中,如果数组包含单词)。

提前致谢。

假设我正确阅读了你的问题并且你能够正确检索用户角色,你正在寻找一种方法来根据用户可以拥有的特定角色授权访问特定路由。

使用管道步骤,您可以完全自由地找出您喜欢的任何实现。您可以在这样的路由上使用 settings 参数:

config.map([
  { 
    route: 'conta', 
    name: 'conta', 
    moduleId: './modules/admin/conta', 
    title: 'accountMessages.account', 
    auth: true,
    settings: {
      role: 'admin' /* or any naming of choice */
    }
  }
]);

然后在管道步骤中,您可以检查此属性并根据用户是否拥有该属性来限制访问:

run(navigationInstruction, next) {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged(user => {
        let currentRoute = navigationInstruction.config;
        let loginRequired = currentRoute.auth && currentRoute.auth === true;

        if (!user && loginRequired) {
          return resolve(next.cancel(new Redirect('')));
        }

        // hasRole checks the user roles for the role set on the route
        if (currentRoute.settings && currentRoute.settings.role) {
           if (!user.hasRole(currentRoute.settings.role) {
              return resolve(next.cancel(new Redirect('')));
           }
        }

        return resolve(next());
      });
    });
  }

您显然可以自由地以任何您喜欢的方式对此进行编码,这更像是一个普遍的想法。