I was recently trying to find a way to deny access to the admin panel in my rails application for users who aren't admin. One way would have been to check the authorisation inline in every action but I was looking for something cleaner.
Meet the before_filter method which helps you keep your controller actions clean and makes it easy to move out the authorisation logic. Here is how it looks
before_filter :admin?
You can also specify if this authorisation check only applies to a certain action, or certain a group of actions of the controller.
before_filter :admin?, :only => :new
before_filter :admin?, :only => [:new, :show]
The conditions on this filter aren't just limited to only, you can also specify except conditions on a before_filter, here is how you'll do it.
before_filter :admin?, :except => :show
before_filter :admin?, :except => [:show, :index]
Now comes the part where you define this admin? method. You can define a helper method in your ApplicationController, and put all your authorisation logic into that. That's all you need to be able to play admin. Happy hacking.
Meet the before_filter method which helps you keep your controller actions clean and makes it easy to move out the authorisation logic. Here is how it looks
before_filter :admin?
You can also specify if this authorisation check only applies to a certain action, or certain a group of actions of the controller.
before_filter :admin?, :only => :new
before_filter :admin?, :only => [:new, :show]
The conditions on this filter aren't just limited to only, you can also specify except conditions on a before_filter, here is how you'll do it.
before_filter :admin?, :except => :show
before_filter :admin?, :except => [:show, :index]
Now comes the part where you define this admin? method. You can define a helper method in your ApplicationController, and put all your authorisation logic into that. That's all you need to be able to play admin. Happy hacking.
No comments:
Post a Comment