2013-07-25 16 views
2

工作,我有一個控制器:skip_before_filter:authenticate_user!不爲AJAX調用

class SessionTimeoutController < ApplicationController 
    # snip 

    skip_before_filter :authenticate_user!, only: [:has_user_timed_out] 

    #snip 

    # Determines whether the user has been logged out due to 
    # inactivity or not. 
    def has_user_timed_out 
    @has_timed_out = (!user_signed_in?) or (current_user.timedout? (user_session["last_request_at"])) 

    respond_to do |format| 
     format.json { render json: @has_timed_out, status: :created} 
    end 
    end 

    #snip 
end 

我使用AJAX請求發送到​​:

$.ajax({ 
    url: '/session_timeout/has_user_timed_out', 
    type: 'GET', 
    dataType: 'json', 
    success: function(logged_out) { 
    if(logged_out === true) 
    { 
     window.location = '/users/sign_in?timedout=1' 
    } 
    else 
    { 
     checkTimeLeft(); 
    } 
    } 
}); 

當這個AJAX調用時,我希望它總是得到響應,即使用戶註銷。我期待這一點,因爲我在控制器中設置了skip_before_filter :authenticate_user!。但是,當我發送AJAX時,服務器會發回一個401 Unauthorized響應。爲什麼是這樣?

此外,當我從瀏覽器控制檯運行這個JS,它按預期工作。我唯一一次遇到AJAX問題的時候是從視圖中調用的。

$.ajax({url: '/session_timeout/has_user_timed_out', type: 'GET', dataType:'JSON', success: function(logged_out) {console.log(logged_out + ' ' + typeof logged_out);}}); 
可能會造成的問題

的一件事是我送的用戶被自動的分一秒內AJAX請求註銷因不活動。這會混淆Devise嗎?


編輯:這是我的Rails日誌的時候我送,結果在一個401響應的請求:

Started GET "/session_timeout/has_user_timed_out" for 10.0.2.2 at 2013-07-25 21:25:51 +0000 
Processing by SessionTimeoutController#has_user_timed_out as JSON 
    ConfigVar Load (0.2ms) SELECT `config_vars`.* FROM `config_vars` WHERE `config_vars`.`name` = 'maintenance_mode' ORDER BY `config_vars`.`id` ASC LIMIT 1 
    User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 14 ORDER BY `users`.`id` ASC LIMIT 1 
Completed 401 Unauthorized in 4ms 

這是我的Rails日誌當我發送的作品的請求,即使用戶被註銷:

Started GET "/session_timeout/has_user_timed_out" for 10.0.2.2 at 2013-07-25 21:29:39 +0000 
Processing by SessionTimeoutController#has_user_timed_out as JSON 
    ConfigVar Load (0.1ms) SELECT `config_vars`.* FROM `config_vars` WHERE `config_vars`.`name` = 'maintenance_mode' ORDER BY `config_vars`.`id` ASC LIMIT 1 
Completed 201 Created in 3ms (Views: 0.1ms | ActiveRecord: 0.1ms) 

玩弄它多一些,它看起來像我第一次發送請求到​​用戶已經被註銷後,失敗的話,不管多麼LON g我等。然後,所有後續請求都成功。

+0

是什麼日誌說? – Substantial

+0

@gg_s:更新了我的問題。 – Kevin

回答

1

我找到了解決方法。 $.ajax可以採用status選項,可以根據響應代碼攔截服務器響應。就我而言,我關心的是在用戶是否登錄一個401錯誤告訴我,該用戶將被註銷,這樣我就可以攔截響應,並採取相應的行動。

$.ajax({ 
    url: '/session_timeout/has_user_timed_out', 
    type: 'GET', 
    dataType: 'json', 
    success: function(logged_out) { 
    if(logged_out === true) 
    { 
     window.location = '/users/timedout' 
    } 
    else 
    { 
     checkTimeLeft(); 
    } 
    }, 
    // THIS IS THE CODE I ADDED FOR MY WORKAROUND: 
    statusCode: { 
    // If we get back an authentication error, it's a 
    // pretty safe bet we're not logged in anymore 
    401: function() { 
     window.location = '/users/timedout' 
    } 
    } 
});