HTTP Basic Auth für Mysql Passwort und das alte old_password in Rails

Veröffentlicht von Edmund Haselwanter am Montag, November 02, 2009

I recently had to develop a small application for a client. The goal was to add a feature to grown Java web application.

As the software was maintained for several years there are users with old an new MySql passwords in the system.

To authenticate the user I have chosen authenticate_or_request_with_http_basic

As I just needed handful of actions all of them go in one controller:

class MyController < ApplicationController
  before_filter :authenticate<pre class="sunburst"><span class="Keyword">class</span> <span class="JEntityNameType">MyController<span class="EntityInheritedClass"> <span class="EntityInheritedClass">&lt;</span> ApplicationController</span></span>
  before_filter <span class="Constant"><span class="Constant">:</span>authenticate</span>

def index

# [ … ]
end

protected def authenticate authenticate_or_request_with_http_basic do |id, password| @user = User.find_by_name(id) login_ok = @user.authenticate(password) login_ok end end

end

To check if the user can be authenticated:

class User < ActiveRecord::Base
  def authenticate(password)
    user = User.find_by_sql(["select * from user where user_pass=password('%s') \
                              OR user_pass=old_password('%s')",password,password])
    (user.length > 0)?true:false
  end


end

Its a very simple approach.

What do you think?