Authlogic Documentation

repository·master·Indexed 26 days ago

https://github.com/binarylogic/authlogic

A Ruby authentication library for Rails providing flexible mechanisms for email/login, passwords, and token-based persistence. It includes features for session management via Authlogic::Session::Base, password hashing with configurable crypto providers, and activity tracking using logged-in status methods and scopes. The library supports ActiveRecord integration through the acts_as_authentic method and provides guidance on migrating from built-in validations to standard Rails validations.

Tokens
9.6K
Snippets
23
Records
64
Agent score
88%

What's inside Authlogic

  1. Implement UserSessionsController

    master

    Create a controller to handle login and logout. The create action should use UserSession.new with permitted parameters including :login, :password, and :remember_me. The destroy action should call current_user_session.destroy.

    class UserSessionsController < ApplicationController
      def new
        @user_session = UserSession.new
      end
    
      def create
        @user_session = UserSession.new(user_session_params.to_h)
        if @user_session.save
          redirect_to root_url
        else
          render :new, status: 422
        end
      end
    
      def destroy
        current_user_session.destroy
        redirect_to new_user_session_url
      end
    
      private
    
      def user_session_params
        params.require(:user_session).permit(:login, :password, :remember_me)
      end
    end
  2. Add UserSession helper methods to ApplicationController

    master

    To access the session and user throughout your application, add current_user_session and current_user helper methods to your ApplicationController and expose them via helper_method.

    class ApplicationController < ActionController::Base
      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
  3. Migrate from Sha512 to SCrypt in Authlogic 3.4.0+

    master

    Starting with version 3.4.0, the default crypto_provider changed from Sha512 to SCrypt. If you have not explicitly configured a crypto_provider and are upgrading, existing user passwords will fail authentication because the library will attempt to verify them using SCrypt instead of Sha512.

    To prevent password breakage, you must either:

    1. Explicitly set the provider to Sha512 to maintain compatibility with existing passwords.
    2. Use the transition_from_crypto_providers option to automatically migrate users to SCrypt as they log in.
    # Option 1: Maintain Sha512 to prevent password breakage
    c.crypto_provider = Authlogic::CryptoProviders::Sha512
    
    # Option 2: Automatically upgrade users from Sha512 to SCrypt upon successful login
    c.transition_from_crypto_providers = [Authlogic::CryptoProviders::Sha512]
    c.crypto_provider = Authlogic::CryptoProviders::SCrypt
  4. Configure Routes for UserSession

    master

    Add the following to your config/routes.rb to support the session resource:

    Rails.application.routes.draw do
      resources :users
      resource :user_session
    end
    Rails.application.routes.draw do
      # ...
      resources :users
      resource :user_session
    end
  5. Migrate from Authlogic validations to ActiveRecord validations

    master

    In Authlogic 4.4.0, built-in validations for email, login, and password are deprecated and will be removed in version 5.0.0. You should migrate to standard ActiveRecord validations to ensure compatibility and better maintainability.

    Migration Steps

    1. Disable Authlogic validations: Update your acts_as_authenticatable configuration block to set the following flags to false:

      • validate_email_field
      • validate_login_field
      • validate_password_field
    2. Implement ActiveRecord validations: Replace Authlogic-specific methods (like validates_length_of_email_field_options) with standard Rails validates calls.

    Recommendation: Replace fields one at a time (e.g., email, then login, then password) and commit each change separately. Complete this migration before upgrading to Authlogic 5.

  6. Configure the Users table migration for Authlogic

    master

    To enable all Authlogic features (Email, Login, Password, PersistenceToken, SingleAccessToken, and PerishableToken), your users table migration should include specific columns and indexes. It also utilizes 'Magic Columns' and 'Magic States' for session management.

    Required columns include:

    • email (unique index)
    • login
    • crypted_password and password_salt
    • persistence_token (unique index)
    • single_access_token (unique index)
    • perishable_token (unique index)
    • Magic Columns: login_count, failed_login_count, last_request_at, current_login_at, last_login_at, current_login_ip
    • Magic States: active, approved, confirmed
    class CreateUser < ActiveRecord::Migration
      def change
        create_table :users do |t|
          # Authlogic::ActsAsAuthentic::Email
          t.string    :email
          t.index     :email, unique: true
    
          # Authlogic::ActsAsAuthentic::Login
          t.string    :login
    
          # Authlogic::ActsAsAuthentic::Password
          t.string    :crypted_password
          t.string    :password_salt
    
          # Authlogic::ActsAsAuthentic::PersistenceToken
          t.string    :persistence_token
          t.index     :persistence_token, unique: true
    
          # Authlogic::ActsAsAuthentic::SingleAccessToken
          t.string    :single_access_token
          t.index     :single_access_token, unique: true
    
          # Authlogic::ActsAsAuthentic::PerishableToken
          t.string    :perishable_token
          t.index     :perishable_token, unique: true
    
          # See "Magic Columns" in Authlogic::Session::Base
          t.integer   :login_count, default: 0, null: false
          t.integer   :failed_login_count, default: 0, null: false
          t.datetime  :last_request_at
          t.datetime  :current_login_at
          t.datetime  :last_login_at
          t.string    :current_login_ip
          t.string    :last_login_ip
    
          # See "Magic States" in Authlogic::Session::Base
          t.boolean   :active, default: false
          t.boolean   :approved, default: false
          t.boolean   :confirmed, default: false
    
          t.timestamps
        end
      end
    end
  7. Implement the User model with acts_as_authentic

    master
    In your User model, call acts_as_authentic to enable Authlogic. Note that in versions 4.4.0 and later, automatic validations for email, login, and password were deprecated, so you should implement your own Rails validations as needed.
  8. Configure password hashing and session behavior

    master

    Within the acts_as_authentic block, you can configure cryptographic providers and session lifecycle behaviors.

    Key configuration options include:

    • crypto_provider: Sets how passwords are hashed (e.g., Authlogic::CryptoProviders::BCrypt).
    • log_in_after_create: Controls whether a user is automatically logged in after successful registration.
    • log_in_after_password_change: Controls whether the session is automatically updated after a password change.
    class User < ApplicationRecord
      acts_as_authentic do |c|
        c.crypto_provider = Authlogic::CryptoProviders::BCrypt
        c.log_in_after_create = false
        c.log_in_after_password_change = false
      end
    end
  9. Enable authentication on an ActiveRecord model with `acts_as_authentic`

    master

    To enable Authlogic authentication features on an ActiveRecord model (typically a User model), call the acts_as_authentic class method. You can optionally provide a block to configure the authentication settings for that specific model.

    Note: Some Authlogic modules require an existing database connection and table. If you call acts_as_authentic before the database is ready, it may raise an error depending on your raise_on_model_setup_error configuration.

    class User < ApplicationRecord
      acts_as_authentic do |c|
        # configuration options go here
      end
    end
  10. Activate Authlogic with a controller object

    master
    Authlogic requires a connection to a controller to function. If you are using a supported framework like Rails, this is handled automatically. If you are using Authlogic in a non-standard environment, you must manually assign a controller object that extends Authlogic::ControllerAdapters::AbstractAdapter to Authlogic::Session::Base.controller.