我使用标准的iron:路由器模式来确保用户在访问路由之前经过身份验证:
authenticatedController = RouteController.extend({
onBeforeAction: function(){
if ( Meteor.user() ){
var route = Router.current().route.getName();
this.next();
} else this.render('login');
})
这适用于非参数化路线,例如:
Router.route("profile",{
name: "profile",
controller: 'authenticatedController'
});
当我尝试将此模式扩展到参数化路线时,例如:
Router.route('/foo/:id',{
name: 'foo',
controller: 'authenticatedController',
data: function(){ return myCollection.findOne({ _id: this.params.id }); } }
});
似乎 beforeAction 在数据功能之后运行。由于 myCollection 在用户登录铁之前不会发布任何文档:路由器决定路由不存在。
我想要404的唯一时间是集合搜索没有返回任何内容。
答案 0 :(得分:0)
我使用以下适用于我的模式:
//I create a hook for authentication
var userAuthHook = function() {
if (Meteor.userId()) {
this.next();
} else {
this.redirect('/login');
}
};
//I apply this hook to all routes except login
Router.onBeforeAction(userAuthHook, {
except: ['login']
});
//if I want a 404 error, I put it in a onAfterAction callback
Router.route('/message/:_id', {
name: 'message',
waitOn: function() {
return [...];
},
onAfterAction: function() {
//we wait for the 'waitOn' data to be ready
if(this.ready()) {
var message = Messages.findOne({_id: this.params._id});
if(!message) {
//if there is no corresponding message we render the 404 template
this.render('error404');
}
}
}
});
我希望这对你也有用。
答案 1 :(得分:0)
我会尝试使用https://github.com/zimme/meteor-iron-router-auth/或GridView
代替Router.go