Securing a Ruby on Rails app

This tutorial is about how to add basic authentication to a RoR app through a simple user table, no ACL or fancier stuff is implemented.

First we need to add a global check to see if a user is already logged in in controllers/application.rb which now looks like this:

class ApplicationController < ActionController::Base
  helper :all
  protect_from_forgery
  filter_parameter_logging :password
  before_filter :check_user

  protected
  def check_user
    if(controller_name != 'user' and action_name != 'login')
      unless session[:cur_username]
        redirect_to('/users/login')
      end
    end
  end

end

Not much to add here, if we don’t have a user session we redirect to users/login (applies to the whole app, there are no public pages/features):

<h1>Login</h1>
<% form_for('login') do %>
  <p>
    Username:<br />
   <%= text_field_tag 'username' %><br />
  </p>
  <p>
    Password:<br />
   <%= password_field_tag 'password' %><br />
  </p>
  <p>
    <%= submit_tag "Login" %>
  </p>
<% end %>
def login
    if session[:cur_username]
      redirect_to('/pages')
    elsif(params[:username] && params[:password])
      cur_user = User.find(:all, :conditions => "username = '#{params[:username]}' AND password = '#{params[:password]}'").first
      if(cur_user)
        session[:cur_username] = cur_user.username
        redirect_to('/pages')
      end
    end
  end

As you can see we don’t really handle a failed login, just show the form again, otherwise we redirect to the application start page, in this case /pages.

We also have a logout function in the users controller:

def logout
    session[:cur_username] = nil
    respond_to do |format|
      format.html
    end
  end

That’s it!


Related Posts

Tags: , ,