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

Meteor Redirect after login and logout

我有一个 Meteor 应用程序,我想让用户在登录和注销后转到仪表板(称为 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. 当我的 webapp 将来增长时,这将变得难以管理(尤其是 onBeforeAction 中的 only 和 except 语句将变得混乱且容易出错)。所以理想情况下,我想结合 requireLogin 挂钩中的所有内容。
  2. 稍后我将使用角色 (alanning:roles)。我将拥有一个 'admin' 角色,一个已注册的 'customer' 角色,然后只是一个只能访问首页的普通访客。在路由器挂钩中使用这个角色有什么想法吗?一个例子将不胜感激。

注意:我使用的是帐户密码包

您可以使用 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
    }
});