I was recently tasked with adding security to a Ruby on Rails project. After asking around and checking some sites, I found that most are using Authlogic.
There is an excellent tutorial at: http://railscasts.com/episodes/160-authlogic
After implementing the gem and steps, I needed to implement admin only pages. Below are the additions:
-- Add this to user.rb ------------------------
def isAdmin?
hasAdminRole = false
for role in self.roles
if role.title == "Administrator"
hasAdminRole = true
end
end
return hasAdminRole
end
-- Add this to application_controller.rb ------------------------
def require_admin
unless logged_in? and current_user.isAdmin?
flash[:notice] = "You must be an administrator to access this page"
redirect_to new_user_session_url
return false
end
end
I created a controller for the admin tasks. After the definition for the class, add the following:
before_filter :require_admin
This will require the user to be in the Administrator role to gain access. If not, it redirects them to the login page with the unauthorized message.