【发布时间】:2014-04-15 22:10:51
【问题描述】:
在我的流星应用程序上,我有一个登录系统,如果你登录或注册成功,它会将你发送到 /dashboard 路径。但是,现在只需输入 localhost:3000/dashboard 即可访问 /dashboard 路径。我怎样才能防止这种情况发生?
【问题讨论】:
标签: html path meteor accounts iron-router
在我的流星应用程序上,我有一个登录系统,如果你登录或注册成功,它会将你发送到 /dashboard 路径。但是,现在只需输入 localhost:3000/dashboard 即可访问 /dashboard 路径。我怎样才能防止这种情况发生?
【问题讨论】:
标签: html path meteor accounts iron-router
我相信你可以使用custom actions for iron-router。您可以在自定义操作中检查Meteor.userId() 是否为null(未登录),并进行相应的重定向。
【讨论】:
您可以使用 before 钩子来完成此操作。这是一个简单的示例,包含三个路由:index、signin 和 dashboard:
Router.map(function() {
this.route('index', {
path: '/'
});
this.route('signin');
this.route('dashboard');
});
var mustBeSignedIn = function() {
if (!(Meteor.user() || Meteor.loggingIn())) {
Router.go('signin');
this.stop();
}
};
Router.before(mustBeSignedIn, {except: ['signin']});
在除signin 之外的所有路由之前,我们会将用户重定向回signin 页面,除非他们已登录或正在登录。您可以在IR 文档的using hooks 部分查看更多示例.
【讨论】:
除了使用路由器挂钩或自定义操作过滤路由外,您还可以确保模板本身只显示给特权用户:
<template name="secret">
{{#if admin}}
...
{{/if}}
</template>
Handlebars.registerHelper('admin', function(options) {
if(Meteor.user() && Meteor.user().admin) return options.fn(this);
return options.inverse(this);
});
如果您想向所有注册用户显示模板,您可以改用{{#if currentUser}},在这种情况下您不需要注册额外的助手。
【讨论】:
您需要在每条路由运行之前检查用户的状态。如果用户未登录(Meteor.userId() 返回 null),则将用户重定向到登录路由。
Router.before(function() {
if (!Meteor.userId()) {
this.redirect('userLoginRoute');
this.stop();
}
}, {
except: ['userLoginRoute', 'userSignupRoute', 'userNewPasswordRoute']
});
【讨论】: