Tôi đã tìm thấy một cách khá thú vị để khắc phục điều này bằng cách sử dụng biến phiên để nhớ người dùng nào đã đăng xuất. Ý tưởng là mặc dù trình duyệt vẫn gửi dữ liệu xác thực, chúng tôi chỉ bỏ qua nó, bởi vì người dùng đã chọn đăng xuất. Bất cứ khi nào một yêu cầu đăng nhập mới được gửi đến trình duyệt, tất cả dữ liệu xác thực sẽ bị xóa, do đó người dùng có thể đăng nhập lại bất kỳ lúc nào.
class ApplicationController < ActionController::Base
# ...
before_filter :authenticate
protected
def authenticate
authenticate_with_http_basic do |username, password|
@current_user = User.find_by_name_and_crypted_password(username, User.digest(password))
@current_user = nil if @current_user && session[:logged_out] == @current_user.id
[email protected]_user.nil?
end
end
def authenticate!
return if @current_user
session[:authenticate_uri] = request.request_uri
redirect_to('/login')
end
end
Sau đó, trên bộ điều khiển sự kiện mà tôi làm:
class EventsController < ApplicationController
before_filter :authenticate!, :only => [ :new, :create, :edit, :update ]
#...
end
Và cuối cùng điều khiển phiên của tôi trông như thế này:
class SessionController < ApplicationController
before_filter :authenticate!, :only => [ :create ]
def create
if session[:authenticate_uri]
redirect_to(session[:authenticate_uri])
session[:authenticate_uri] = nil
else
redirect_to(new_event_path)
end
end
def destroy
session[:logged_out] = @current_user.id
redirect_to '/'
end
protected
def authenticate!
authenticate_or_request_with_http_basic("Rankings") do |username, password|
@current_user = User.find_by_name_and_crypted_password(username, User.digest(password))
if @current_user && session[:logged_out] == @current_user.id
@current_user = nil
session[:logged_out] = nil
end
[email protected]_user.nil?
end
end
end
Và đừng quên các tuyến đường của bạn!
map.logout 'login', :controller => 'session', :action => 'create'
map.logout 'logout', :controller => 'session', :action => 'destroy'
Nguồn
2009-07-08 21:00:11
Sessions không RESTful. – deamon