My own authlogic playground, with Rails 3 info from this post, plus bits of other functionality/explanation.
gem 'authlogic'
gem 'rails3-generators'
Run bundle install
as usual.
rails g authlogic:session UserSession --fixture=false
This creates an empty UserSession
model that derives from Authlogic::Session::Base
. We add the
--fixture=false
to prevent the creation of a user_sessions.yml
fixture file. If the file is created, when tests are run, Rails will try to delete the data from a non-exstent user_sessions table, causing test failure.
Authlogic user sessions look like ActiveRecord models, but aren't--they're not backed by a table. They're an AR-like mapping of a user's sessions.
We'll assume our user model is named User
(creative!). If we already have one, we can add a bunch of fields to it via a migration, otherwise we'll create a new one.
t.string :login, :null => false
t.string :email, :null => false
t.string :crypted_password, :null => false
t.string :password_salt, :null => false
t.string :persistence_token, :null => false
There are a number of optional fields. See the user migration file or read the actual docs for further info.
class User < ActiveRecord::Base
acts_as_authentic
end
Pass a block to acts_as_authentic
to configure authlogic parameters. For example, during testing, I disabled password confirmation to make things easier.
acts_as_authentic do |c|
c.require_password_confirmation = false
end
More discussion of the code below lives at the link at the top of the readme; I copied it largely verbatim.
- routes (login, logout, home page)
- application controller (helpers)
- session controller (login, logout)
- home controller (index page,
before_filter
to require login) - session views (Login form)
We'll use rails console
to create our first user. (Note There's also a user in the seeds.rb
file.)
pry(main)> User.create(:login => 'login1', :password => 'login1', :email => '[email protected]').save!
By default, authlogic requires an email address, and validates the password length.
Configure the validations in the acts_as_authentic
block as detailed above. The docs list the defaults, but we can also spelunk using Pry and see for ourselves.
pry(main)> cd User
pry(#<Class:0x1041dcc20>):1> validates_length_of_password_field_options
=> {:minimum=>4, :if=>:require_password?}
pry(#<Class:0x1041dcc20>):1> validates_format_of_email_field_options
=> {:with=>/^[A-Z0-9_\.%\+\-']+@(?:[A-Z0-9\-]+\.)+(?:[A-Z]{2,4}|museum|travel)$/i, :message=>"should look like an email address."}
pry(#<Class:0x1041dcc20>):1> validates_length_of_email_field_options
=> {:maximum=>100}
The length validations accepts the usual length validation hash options.