在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
本文介绍了如何在Rails应用中实现一个更友好的登录系统。当未登录的用户尝试访问受保护页面时,系统会引导他们先进行登录,并在登录成功后返回到他们最初请求的页面。文章详细展示了如何通过修改授权和登录方法来实现这一功能。
2103

被折叠的 条评论
为什么被折叠?



