Brian's Blog

items I see across my tribes

Rails Authentication

April 14
by briancarter 14. April 2011 14:25

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.

Categories: Development


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.