= Authlogic

Authlogic is a clean, simple, and unobtrusive ruby authentication solution.

A code example can replace a thousand words...

Authlogic introduces a new type of model. You can have as many as you want, and name them whatever you want, just like your other models. In this example, we want to authenticate with the User model, which is inferred by the name:

  class UserSession < Authlogic::Session::Base
    # specify configuration here, such as:
    # logout_on_timeout true
    # ...many more options in the documentation
  end

Log in with any of the following. Create a UserSessionsController and use it just like your other models:

  UserSession.create(:login => "bjohnson", :password => "my password", :remember_me => true)
  session = UserSession.new(:login => "bjohnson", :password => "my password", :remember_me => true); session.save
  UserSession.create(:openid_identifier => "identifier", :remember_me => true) # requires the authlogic-oid "add on" gem
  UserSession.create(my_user_object, true) # skip authentication and log the user in directly, the true means "remember me"

The above handles the entire authentication process for you. It first authenticates, then it sets up the proper session values and cookies to persist the session. Just like you would if you rolled your own authentication solution.

You can also log out / destroy the session:

  session.destroy

After a session has been created, you can persist it across requests. Thus keeping the user logged in:

  session = UserSession.find

To get all of the nice authentication functionality in your model just do this:

  class User < ActiveRecord::Base
    acts_as_authentic do |c|
      c.my_config_option = my_value
    end # the configuration block is optional
  end

This handles validations, etc. It is also "smart" in the sense that it if a login field is present it will use that to authenticate, if not it will look for an email field, etc. This is all configurable, but for 99% of cases that above is all you will need to do.

Also, sessions are automatically maintained. You can switch this on and off with configuration, but the following will automatically log a user in after a successful registration:

  User.create(params[:user])

This also updates the session when the user changes his/her password.

Authlogic is very flexible, it has a strong public API and a plethora of hooks to allow you to modify behavior and extend it. Check out the helpful links below to dig deeper.

== Helpful links

* <b>Documentation:</b> http://rdoc.info/projects/binarylogic/authlogic
* <b>Repository:</b> http://github.com/binarylogic/authlogic/tree/master
* <b>Railscasts Screencast:</b> http://railscasts.com/episodes/160-authlogic
* <b>Live example with OpenID "add on":</b> http://authlogicexample.binarylogic.com
* <b>Live example repository with tutorial in README:</b> http://github.com/binarylogic/authlogic_example/tree/master
* <b>Tutorial: Reset passwords with Authlogic the RESTful way:</b> http://www.binarylogic.com/2008/11/16/tutorial-reset-passwords-with-authlogic
* <b>Issues:</b> http://github.com/binarylogic/authlogic/issues
* <b>Google group:</b> http://groups.google.com/group/authlogic

<b>Before contacting me directly, please read:</b>

If you find a bug or a problem please post it in the issues section. If you need help with something, please use google groups. I check both regularly and get emails when anything happens, so that is the best place to get help. This also benefits other people in the future with the same questions / problems. Thank you.

== Authlogic "add ons"

* <b>Authlogic OpenID addon:</b> http://github.com/binarylogic/authlogic_openid
* <b>Authlogic LDAP addon:</b> http://github.com/binarylogic/authlogic_ldap
* <b>Authlogic Facebook Connect:</b> http://github.com/kalasjocke/authlogic_facebook_connect
* <b>Authlogic OAuth (Twitter):</b> http://github.com/jrallison/authlogic_oauth

If you create one of your own, please let me know about it so I can add it to this list. Or just fork the project, add your link, and send me a pull request.

== Session bugs (please read if you are having issues with logging in / out)

Apparently there is a bug with apache / passenger for v2.1.X with sessions not working properly. This is most likely your problem if you are having trouble logging in / out. This is *not* an Authlogic issue. This can be solved by updating passener or using an alternative session store solution, such as active record store.

== Documentation explanation

You can find anything you want about Authlogic in the {documentation}[http://authlogic.rubyforge.org], all that you need to do is understand the basic design behind it.

That being said, there are 2 models involved during authentication. Your Authlogic model and your ActiveRecord model:

1. <b>Authlogic::Session</b>, your session models that extend Authlogic::Session::Base.
2. <b>Authlogic::ActsAsAuthentic</b>, which adds in functionality to your ActiveRecord model when you call acts_as_authentic.

Each of the above has its various sub modules that contain common logic. The sub modules are responsible for including *everything* related to it: configuration, class methods, instance methods, etc.

For example, if you want to timeout users after a certain period of inactivity, you would look in <b>Authlogic::Session::Timeout</b>. To help you out, I listed the following publicly relevant modules with short descriptions. For the sake of brevity, there are more modules than listed here, the ones not listed are more for internal use, but you can easily read up on them in the {documentation}[http://authlogic.rubyforge.org].

=== Authlogic::ActsAsAuthentic sub modules

These modules are for the ActiveRecord side of things, the models that call acts_as_authentic.

* <b>Authlogic::ActsAsAuthentic::Base</b> - Provides the acts_as_authentic class method and includes all of the submodules.
* <b>Authlogic::ActsAsAuthentic::Email</b> - Handles everything related to the email field.
* <b>Authlogic::ActsAsAuthentic::LoggedInStatus</b> - Provides handy named scopes and methods for determining if the user is logged in or out.
* <b>Authlogic::ActsAsAuthentic::Login</b> - Handles everything related to the login field.
* <b>Authlogic::ActsAsAuthentic::MagicColumns</b> - Handles everything related to the "magic" fields: login_count, failed_login_count, last_request_at, etc.
* <b>Authlogic::ActsAsAuthentic::Password</b> - This one is important. It handles encrypting your password, salting it, etc. It also has support for transitioning password algorithms.
* <b>Authlogic::ActsAsAuthentic::PerishableToken</b> - Handles maintaining the perishable token field, also provides a class level method for finding record using the token.
* <b>Authlogic::ActsAsAuthentic::PersistenceToken</b> - Handles maintaining the persistence token. This is the token stored in cookies and sessions to persist the users session.
* <b>Authlogic::ActsAsAuthentic::RestfulAuthentication</b> - Provides configuration options to easily migrate from the restful_authentication plugin.
* <b>Authlogic::ActsAsAuthentic::SessionMaintenance</b> - Handles automatic session maintenance. EX: a new user registers, automatically log them in. Or a user changes their password, update their session.
* <b>Authlogic::ActsAsAuthentic::SingleAccessToken</b> - Handles maintaining the single access token.
* <b>Authlogic::ActsAsAuthentic::ValidationsScope</b> - Allows you to scope all validations, etc. Just like the :scope option for validates_uniqueness_of

=== Authlogic::Session sub modules

These modules are for the models that extend Authlogic::Session::Base.

* <b>Authlogic::Session::BruteForceProtection</b> - Disables accounts after a certain number of consecutive failed logins attempted.
* <b>Authlogic::Session::Callbacks</b> - Your tools to extend, change, or add onto Authlogic. Lets you hook in and do just about anything you want. Start here if you want to write a plugin or add-on for Authlogic
* <b>Authlogic::Session::Cookies</b> - Authentication via cookies.
* <b>Authlogic::Session::Existence</b> - Creating, saving, and destroying objects.
* <b>Authlogic::Session::HttpAuth</b> - Authentication via basic HTTP authentication.
* <b>Authlogic::Session::Id</b> - Allows sessions to be separated by an id, letting you have multiple sessions for a single user.
* <b>Authlogic::Session::MagicColumns</b> - Maintains "magic" database columns, similar to created_at and updated_at for ActiveRecord.
* <b>Authlogic::Session::MagicStates</b> - Automatically validates based on the records states: active?, approved?, and confirmed?. If those methods exist for the record.
* <b>Authlogic::Session::Params</b> - Authentication via params, aka single access token.
* <b>Authlogic::Session::Password</b> - Authentication via a traditional username and password.
* <b>Authlogic::Session::Persistence</b> - Persisting sessions / finding sessions.
* <b>Authlogic::Session::Session</b> - Authentication via the session, the controller session that is.
* <b>Authlogic::Session::Timeout</b> - Automatically logging out after a certain period of inactivity.
* <b>Authlogic::Session::UnauthorizedRecord</b> - Handles authentication by passing an ActiveRecord object directly.
* <b>Authlogic::Session::Validation</b> - Validation / errors.

=== Miscellaneous modules

Miscellaneous modules that shared across the authentication process and are more "utility" modules and classes.

* <b>Authlogic::AuthenticatesMany</b> - Responsible for allowing you to scope sessions to a parent record. Similar to a has_many and belongs_to relationship. This lets you do the same thing with sessions.
* <b>Authlogic::CryptoProviders</b> - Contains various encryption algorithms that Authlogic uses, allowing you to choose your encryption method.
* <b>Authlogic::I18n</b> - Acts JUST LIKE the rails I18n library, and provides internationalization to Authlogic.
* <b>Authlogic::Random</b> - A simple class to generate random tokens.
* <b>Authlogic::Regex</b> - Contains regular expressions used in Authlogic. Such as those to validate the format of the log or email.
* <b>Authlogic::TestCase</b> - Various helper methods for testing frameworks to help you test your code.
* <b>Authlogic::Version</b> - A handy class for determine the version of Authlogic in a number of ways.

== Quick Rails example

What if creating sessions worked like an ORM library on the surface...

  UserSession.create(params[:user_session])

What if your user sessions controller could look just like your other controllers...

  class UserSessionsController < ApplicationController
    def new
      @user_session = UserSession.new
    end
    
    def create
      @user_session = UserSession.new(params[:user_session])
      if @user_session.save
        redirect_to account_url
      else
        render :action => :new
      end
    end
    
    def destroy
      current_user_session.destroy
      redirect_to new_user_session_url
    end
  end

As you can see, this fits nicely into the RESTful development pattern. What about the view...

  <% form_for @user_session do |f| %>
    <%= f.error_messages %>
    <%= f.label :login %><br />
    <%= f.text_field :login %><br />
    <br />
    <%= f.label :password %><br />
    <%= f.password_field :password %><br />
    <br />
    <%= f.submit "Login" %>
  <% end %>

Or how about persisting the session...

  class ApplicationController
    helper_method :current_user_session, :current_user
    
    private
      def current_user_session
        return @current_user_session if defined?(@current_user_session)
        @current_user_session = UserSession.find
      end
      
      def current_user
        return @current_user if defined?(@current_user)
        @current_user = current_user_session && current_user_session.user
      end
  end

== Install & Use

Install the gem / plugin (recommended)

From rubyforge:

  $ sudo gem install authlogic

Or from github:

  $ sudo gem install binarylogic-authlogic

Now just add the gem dependency in your projects configuration.

Or you can install this as a plugin:

  script/plugin install git://github.com/binarylogic/authlogic.git

== Detailed Setup Tutorial

See the {authlogic example}[http://github.com/binarylogic/authlogic_example/tree/master] for a detailed setup tutorial. I did this because not only do you have a tutorial to go by, but you have an example app that uses the same tutorial, so you can play around with with the code. If you have problems you can compare the code to see what you are doing differently.

== Testing

I think one of the best aspects of Authlogic is testing. For one, it cuts out <b>a lot</b> of redundant tests in your applications because Authlogic is already thoroughly tested for you. It doesn't include a bunch of tests into your application, because it comes tested, just like any other library.

For example, think about ActiveRecord. You don't test the internals of ActiveRecord, because the creators of ActiveRecord have already tested the internals for you. It wouldn't make sense for ActiveRecord to copy it's hundreds of tests into your applications. The same concept applies to Authlogic. You only need to test code you write that is specific to your application, just like everything else in your application.

That being said, testing your code that uses Authlogic is easy. Since everyone uses different testing suites, I created a helpful module called Authlogic::TestCase, which is basically a set of tools for testing code using Authlogic. I explain testing Authlogic thoroughly in the {Authlogic::TestCase section of the documentation}[http://rdoc.info/rdoc/binarylogic/authlogic/blob/f2f6988d3b97e11770b00b72a7a9733df69ffa5b/Authlogic/TestCase.html]. It should answer any questions you have in regards to testing Authlogic.

== Tell me quickly how Authlogic works

Interested in how all of this all works? Think about an ActiveRecord model. A database connection must be established before you can use it. In the case of Authlogic, a controller connection must be established before you can use it. It uses that controller connection to modify cookies, the current session, login with HTTP basic, etc. It connects to the controller through a before filter that is automatically set in your controller which lets Authlogic know about the current controller object. Then Authlogic leverages that to do everything, it's a pretty simple design. Nothing crazy going on, Authlogic is just leveraging the tools your framework provides in the controller object.

== What sets Authlogic apart and why I created it

What inspired me to create Authlogic was the messiness of the current authentication solutions. Put simply, they just didn't feel right, because the logic was not organized properly. As you may know, a common misconception with the MVC design pattern is that the model "M" is only for data access logic, which is wrong. A model is a place for domain logic. This is why the RESTful design pattern and the current authentication solutions don't play nice. Authlogic solves this by placing the session maintenance logic into its own domain (aka "model"). Moving session maintenance into its own domain has its benefits:

1. <b>It's cleaner.</b> There are no generators in Authlogic. Authlogic provides a class that you can use, it's plain and simple ruby. More importantly, the code in your app is code you write, written the way you want, nice and clean. It's code that should be in your app and is specific to your app, not a redundant authentication pattern.
2. <b>Easier to stay up-to-date.</b> To make my point, take a look at the commits to any other authentication solution, then look at the {commits for authlogic}[http://github.com/binarylogic/authlogic/commits/master]. How many commits could you easily start using if you already had an app using that solution? With an alternate solution, very few, if any. All of those cool new features and bug fixes are going to have be manually added or wait for your next application. Which is the main reason a generator is not suitable as an authentication solution. With Authlogic you can start using the latest code with a simple update of a gem. No generators, no mess.
3. <b>It ties everything together on the domain level.</b> Take a new user registration for example, no reason to manually log the user in, authlogic handles this for you via callbacks. The same applies to a user changing their password. Authlogic handles maintaining the session for you.
4. <b>No redundant tests.</b> Because Authlogic doesn't use generators, #1 also applies to tests. Authlogic is *thoroughly* tested for you. You don't go and test the internals of ActiveRecord in each of your apps do you? So why do the same for Authlogic? Your application tests should be for application specific code. Get rid of the noise and make your tests focused and concise, no reason to copy tests from app to app.
5. <b>Framework agnostic</b>. Authlogic can be used in *any* ruby framework you want: Rails, Merb, Sinatra, Mack, your own framework, whatever. It's not tied down to Rails. It does this by abstracting itself from these framework's controllers by using a controller adapter. Thanks to {Rack}[http://rack.rubyforge.org/], there is a defined standard for controller structure, and that's what Authlogic's abstract adapter follows. So if your controller follows the rack standards, you don't need to do anything. Any place it deviates from this is solved by a simple adapter for your framework that closes these gaps. For an example, checkout the Authlogic::ControllerAdapters::MerbAdapter.
5. <b>You are not restricted to a single session.</b> Think about Apple's me.com, where they need you to authenticate a second time before changing your billing information. Why not just create a second session for this? It works just like your initial session. Then your billing controller can require an "ultra secure" session.
6. <b>Easily extendable.</b> One of the distinct advantages of using a library is the ability to use its API, assuming it has one. Authlogic has an *excellent* public API, meaning it can easily be extended and grow beyond the core library. Checkout the "add ons" list above to see what I mean.


Copyright (c) 2009 {Ben Johnson of Binary Logic}[http://www.binarylogic.com], released under the MIT license