2013-03-21 49 views
3

確保用戶登錄到Ember應用程序的最佳方式是什麼?確保用戶在Ember應用程序中登錄

我想在路由激動之前攔截任何URL,顯示帶有user_id /密碼的模式彈出窗口,並轉到原始URL。

也許類似於Rail的application_controller#before_filter,它在任何其他控制器方法之前執行。

我有以下路徑:

App.Router.map(function(){ 
    this.resource('folder', {path: '/'}, function(){ 
     this.resource('files', {path: '/:folder_id'}, function(){ 
      this.route('index'); 
     }); 
    }); 
}); 

我試圖建立ApplicationRoute:

App.ApplicationRoute = Ember.Route.extend({ 
    activate: function(){ 
     console.log("activating app route"); 
    } 
}); 

但問題是,如果我打index.html#/folder01folder路線是application路線之前執行。

總結工作流程的理想應該是這樣:

  1. 用戶點擊index.html#/folder01 URL
  2. 應用程序檢查用戶是否登錄如果沒有模式彈出出現
  3. 登錄後,應用程序應該呈現index.html#/folder01 URL

非常感謝!

+0

請看[this](http://stackoverflow.com/questions/15416143/ember-js-authentication/15429584#15429584)especialy the redirect method – pjlammertyn 2013-03-21 19:19:44

回答

0

您可以使用您的路線來實現:

App.DatasetEditRoute = Ember.Route.extend({ 
    redirect: function() { 
    if (this.controllerFor('currentUser').get('isSignedIn') === false) { 
     this.transitionTo('user.login'); 
    } 
    } 
}); 
1

看起來像我發現一個可行的解決方案。那就是:

App.Router.reopen({ 
    startRouting: function() { 
     if (!App.userProfile.get('loggedIn')) { 
      $("#login_dialog").modal('show').one('click', "#login_btn", function(){ 
       $("#login_dialog").modal('hide'); 
       App.userProfile.set('loggedIn', true); 
       App.startRouting(); 
      }); 
     } else { 
      this._super(); 
     } 
    } 
}); 

如果應用程序檢測會話超時,則執行window.location.reload()。將很高興有App.reset()工作,但afaik它尚未正確實施。

我不是100%確定此解決方案沒有像內存泄漏或類似的問題。我很想聽聽Ember專家對這種方法的看法。

感謝

0

我創建userapp-ember這對用戶身份驗證的Ember.js模塊。它的意思是UserApp,但是它是開源的,所以你可以修改它來使用你自己的服務,如果你願意的話。

爲了證明我簡短如何解決了這個問題:

App.ProtectedRouteMixin = Ember.Mixin.create({ 
    beforeModel: function(transition) { 
    // check if the user if authenticated 
    if (!isAuthenticated) { 
     transition.abort(); 
     this.transitionTo('login'); // transition to the login route 
    } 
    } 
}); 

App.IndexRoute = Ember.Route.extend(App.ProtectedRouteMixin); 

我用一個mixin擴展,我想保護的所有路由。如果用戶未登錄,mixin將監聽beforeModel事件並中止轉換(isAuthenticated)。然後,而不是重定向到登錄路線,而是可以顯示登錄彈出窗口。登錄成功後,重新加載頁面或轉換到相同的路由。