2015-04-14 50 views
1

我使用標準鐵:鐵:路由器beforeAction登錄和數據:函數?

authenticatedController = RouteController.extend({ 
    onBeforeAction: function(){ 
    if (Meteor.user()){ 
     var route = Router.current().route.getName(); 
     this.next(); 
    } else this.render('login'); 
}) 

這非常適用於unparameterized路線,例如:

Router.route("profile",{ 
    name: "profile", 
    controller: 'authenticatedController' 
}); 

當我確保用戶正在訪問的路線之前要驗證路由器模式嘗試這種模式延伸到參數化途徑,例如:

Router.route('/foo/:id',{ 
    name: 'foo', 
    controller: 'authenticatedController', 
    data: function(){ return myCollection.findOne({ _id: this.params.id }); } } 
}); 
  1. 它的工作原理,如果用戶在
  2. 已經登錄我得到的404頁面,如果用戶不登錄

似乎beforeAction運行數據功能後。由於myCollection在用戶登錄之前不會發布任何文檔iron:路由器決定路由不存在。

我想要一個404的唯一時間是如果集合搜索沒有返回任何東西。

+0

沒有你試穿Router.configure? 'notFoundTemplate:'notFound','和鉤子'Router.onBeforeAction('dataNotFound',{only:'profile'});' – Ethaan

+0

感謝Ethann - 我有'notFoundTemplate:'notFound' - 這就是我的404如何顯示。我沒有嘗試'Router.onBeforeAction('dataNotFound',{only:'profile'});'因爲我實際上想要一個404如果id不存在(或者有人在切割/粘貼URL) –

回答

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

Merci Guilllaume。使用'onAfterAction'來處理404s是非常有用的。但是,您的模式不會爲模板設置數據上下文。我仍然需要在模板助手中設置數據上下文,而不是從路由器獲取數據上下文。另外,如果您在'beforeAction'鉤子中執行'this.redirect('login')'而不是'this.render('login'),那麼登錄後用戶將不會被帶到預期的路線。 –

相關問題