登录和注销后的流星重定向



我有一个流星应用程序,我想让用户去一个仪表板(称为documentsIndex)页面后登录和注销,重定向到web应用程序的首页。现在我有以下内容:

Iron.Router.hooks.requireLogin = function () {
  if (! Meteor.user()) {
    if (Meteor.loggingIn()) {
      this.render('this.loadingTemplate');
    } else {
      this.render('accessDenied');
    }
  } else {
    this.next();
  }
};
Iron.Router.hooks.goToDashboard = function () {
  if (Meteor.user()) {
    Router.go('documentsIndex');
    this.next();
  } else {
    this.next();
  }
};
Iron.Router.hooks.goToFrontpage= function () {
  if (!Meteor.user()) {
    Router.go('frontpage');
    this.next();
  } else {
    this.next();
  }
};
Router.onBeforeAction('goToDashboard', {except: ['documentNew', 'documentIndex', 'documentShow', 'documentEdit']});
Router.onBeforeAction('goToFrontpage', {except: ['frontpage', 'about']});
Router.onBeforeAction('requireLogin', {except: ['frontpage', 'about']});
Router.onBeforeAction('dataNotFound', {only: ['documentIndex','documentNew', 'documentIndex', 'documentShow', 'documentEdit']});

这是有效的,所以当用户登录时,他总是被重定向到DocumentsIndex路由,并且他可以导航后端。当用户注销时,他被重定向到首页,并可以浏览前端。

  1. 当我的web应用程序将在未来增长时,这很难管理(特别是onBeforeAction中的only和except语句将变得混乱和容易出错)。所以理想情况下,我想结合requireLogin钩子中的所有内容。
  2. 稍后我将使用角色(alanning:roles)。我将有一个'管理员'的角色,一个注册的'客户'的角色,然后只是一个普通的访客,只能访问首页。在Router钩子中使用这个角色有什么想法吗?请举个例子。

注意:我使用帐户密码包

你可以使用Meteor的Accounts.onLogin(function () {});钩子来代替iron:router (doc)。在这个钩子中,您可以访问Meteor.user()来检查它们的角色,并根据需要更改操作。

同样,您可以使用Meteor.logout()中的回调函数来处理注销时的任何逻辑,如下所示:

Meteor.logout(function(err) {
  // logout logic here
});

如果你想要这个注销钩子在你注销的时候触发{{> loginButtons}}在一个特定的模板,如:adminTemplate,然后使用下面的代码。我还没有测试过这个代码片段,所以可能需要做一些小的调整。

Template.adminTemplate.events({
    'click #login-buttons-logout': function (event) {
        //add your custom logic on top of this
       //the default behaviour should still happen from meteor
    }
});

最新更新