RSS Feed

RailsAdmin Authentication with Authlogic

Posted on Tuesday, June 28, 2011 in Uncategorized

If you have been building a Ruby on Rails application recently, you may have heard of rails_admin which generates an administration backend and allows you to conveniently administer your Rails models. I have found it to be very functional and looks good while doing so.

There is just one issue with RailsAdmin; it is very tightly coupled with the devise authentication solution. Devise is a rack-based authentication solution for Rails based on Warden. RailsAdmin requires you to have the devise gem installed. But before there was devise, there was authlogic, and I was not going to let RailsAdmin’s tight coupling with devise stop me from using it.

RailsAdmin makes provision for you to add your own authentication and authorization scheme. I am going to demonstrate how to do this with authlogic (assuming you have already followed the instructions for installing rails_admin). You will need to create a new file in your config/initializers directory, lets call it rails_admin.rb

Inside this file, we are going to add the following code:

RailsAdmin.authenticate_with{
  unless current_user
    session[:return_to] = request.url
    redirect_to login_url, :alert => "You must first log in or sign up before accessing this page."
  end
}

RailsAdmin.authorize_with{
  redirect_to root_path, :alert => "You are not authorized to access that page" unless current_user.admin?
}

A few comments to the code:

  1. RailsAdmin will use the code in the first block to authenticate your users (who-are-you) and the code in the second block will check authorization to the admin section (what-can-you-do).
  2. The current_user method returns nil if no user is currently logged in.
  3. I store the request url before sending the user to the login page, because the user session controller can use it to redirect the user back to the admin page after login.
  4. For the authorization block, I assume that your User model has a boolean attribute called admin which can be checked to make sure that the user is an administrator before allowing access.

So there you have it, now restart your application and your /admin page should redirect you to the login page or deny you access if you are not an admin.

Share and Enjoy:
  • Twitter
  • Google Bookmarks
  • Digg
  • del.icio.us
  • Facebook

Be the first to comment.

Leave a Reply