在ASP.NET裡面,通過設定強制登入可以讓沒有登入的使用者首先跳轉到登入頁面,然後可以設定讓使用者登入後自動跳轉到使用者想要浏覽的網頁。同樣,在Rails裡面一樣可以實作,實作過程如下:
A Friendlier Login System
As the code stands now, if an administrator tries to access a restricted
page before they are logged in, they are taken to the login page. When
they then log in, the standard status page is displayed—their original
request is forgotten. If you want, you can change the applicaton to forward
them to their originally-requested page once they log in.
First, in the authorize( ) method, remember the incoming request’s URI in
the session if you need to log the user in.
def authorize
unless User.find_by_id(session[:user_id])
session[:original_uri] = request.request_uri
flash[:notice] = "Please log in"
redirect_to(:controller => "login" , :action => "login" )
end
end
Once we log someone in, we can then check to see if there’s a URI stored
in the session and redirect to it if so.
def login
session[:user_id] = nil
if request.post?
user = User.login(params[:name], params[:password])
if user
session[:user_id] = user.id
redirect_to(session[:original_uri] || { :action => "index" })
else
flash[:notice] = "Invalid user/password combination"
end
end
end