I've recently been playing around with Authlogic (API), and it does a great job of handling a lot of things for you automatically, including the field used for the username. In fact all you need to do is have a field called login or username in the table of the object you're authorizing against and, hey presto, Authlogic assumes it's the username for your user and takes care of it. But what if you want to use an alternative field, let's say "screen_name".
Let's say you have an object User that you're authenicating against. The migration might look like this
def self.up
create_table :users do |t|
t.string :screen_name, :null => false
t.string :email, :null => false
t.string :first_name, :null => false
t.string :last_name, :null => false
t.string :crypted_password, :null => false
t.string :password_salt, :null => false
t.string :persistence_token, :null => false
t.string :single_access_token, :null => false
t.string :perishable_token, :null => false
t.timestamps
end
and you app/models/user.rb might look like this
class User < ActiveRecord::Base
acts_as_authentic
end
To make sure Authlogic uses :screen_name as the username field change user.rb to
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.login_field = :screen_name
end
end
Easy. the field "screen_name" can now be used to log in users and Authlogic will make sure it's unique and valid.
Now, I don't like the default validations for the username, it allows spaces and other symbols and it's anywhere from 3 to 100 characters. I want to have only letters and numbers and screen names between 5 and 20 characters. Once again change user.rb to
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.login_field = :screen_name
c.validates_format_of_login_field_options = {:with => /^[a-zA-Z0-9]+$/, :message => I18n.t('error_messages.login_invalid', :default => "should use only letters and numbers, no other characters.")}
c.validates_length_of_login_field_options = {:within => 5..20}
end
end
validates_format_of_login_field_options allows us to tell Authlogic how to validate the contents of "screen_name". In this case it's letters and number only. If it;s not valid it'll throw a login_invalid error with the message "should use only letters and numbers, no other characters.". For more options see the Rails validates_format_of API.
validates_length_of_login_field_options tells Authlogic how many characters the field should contain (in this case between 5 and 20). For more options see the Rails validates_length_of API.
Once again, nice and easy. Thanks Authlogic.