how to add an interstitial page to prompt a user to enter a password before seeing Page#Show
right now my app has a Pages model. Anyone with the url, /pages/3 can view a page. I want to make makes have the option of public or private.
If p开发者_如何转开发ublic anyone with the URL can view.
If the page if private, only users that enter a password should be able to view the page.
Right now the page is rendered with the Page#Show controller. What's the right way to go about handling this so that when a user tries to access a private page they first need to enter a password correctly and then they can view the page? How would I structure this in the controller?
Thanks
Since you are using cancan:
def show
@page = Page.find(params[:id])
authorize! :read, @page
end
This will raise a CanCan::AccessDenied
error (if the user isn't logged in or isn't authorized), which can be caught like so (docs):
class ApplicationController < ActionController::Base
rescue_from CanCan::AccessDenied do |exception|
# Save the requested path in the user's session
session[:return_to] = request.fullpath
# Send the user to the sign in page
redirect_to sign_in_path, :alert => exception.message
end
end
Depending on your authentication system, on a successful sign-in, in your sessions controller you can:
redirect_to session[:return_to] || your_default_after_sign_in_path
# Clear the :return_to value
session[:return_to] = nil
I may be missing some details, but this is the gist of it. Best of luck.
EDIT: I should attribute the friendly forwarding part of my answer to Michael Hartl and his book.
Looks like you need an authorization solution. I recommend CanCan its pretty flexible. You can probably tweak it to use "Pages" as the resource that you "login" to instead of the standard "users" if you don't already have authentication and/or don't want authentication per user.
精彩评论