kakubei
kakubei

Reputation: 5400

Rails allow access to one page without restricting the whole controller

So I have 3 types of users:

admin
moderator
regular user

I have the moderator and admin pages locked with a controller-wide system like this:

def authorize
  unless User.find_by_id(session[:user_id]) and User.find_by_id(session[:user_id]).moderator == true
    redirect_to login_url, :notice => "Please log in with a moderator account"
  end
end

def authorize_admin
  unless User.find_by_id(session[:user_id]) and User.find_by_id(session[:user_id]).admin == 1
    redirect_to login_url, :notice => "Only admins can access the page you tried to access"
  end
end

But I need to give access to the regular user to the edit pages (and of course the update action) of multiple controllers. But just edit and update.

If I do:

before_filter :authorize, :except => :edit

Then anyone (even if not logged in) has access to those pages.

How would I go about doing something like that?

Edit

As per Thilo's suggestion, I added the following to the application_controller.erb file:

  def update_successful
    skip_before_filter :authorize
  end

To be able to serve the update_successful page after a regular user has edited an entry. However I get this error:

undefined method `skip_before_filter' for #<HomeController:0x007ff782aeb6f0>

Upvotes: 2

Views: 1775

Answers (1)

Thilo
Thilo

Reputation: 17735

You can skip any globally applies filter explicitly:

skip_before_filter :authorize, :only => [:edit, :update]

Or don't apply it to the relevant actions in the first place:

before_filter :authorize, :except => [:edit, :update]

EDIT

To answer your further question: Add this to your application controller:

def upload_successful
end

This is an empty method that explicitly defines the action that so far as been implicitly be used by Rails when rendering the home/upload_successful.html.haml template. Then, remove authentication from that method by modifying your filter:

before_filter :authorize, :except => [:upload_successful]

Here's a good introduction to rendering in Rails - it helps to understand rendering by default, which is what your upload_successful template has been displayed without having a matching controller or action defined.

Upvotes: 2

Related Questions