在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
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