Define the UserSession model
masterAuthlogic requires a session model that inherits from Authlogic::Session::Base. Create this file at app/models/user_session.rb.
class UserSession < Authlogic::Session::Base
endrepository·master·Indexed 26 days ago
https://github.com/binarylogic/authlogicA 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.
Authlogic requires a session model that inherits from Authlogic::Session::Base. Create this file at app/models/user_session.rb.
class UserSession < Authlogic::Session::Base
endTo install Authlogic in your Ruby project, add the gem to your Gemfile and run bundle install.
gem 'authlogic'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
endTo 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
endStarting 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:
Sha512 to maintain compatibility with existing passwords.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::SCryptAdd the following to your config/routes.rb to support the session resource:
Rails.application.routes.draw do
resources :users
resource :user_session
endRails.application.routes.draw do
# ...
resources :users
resource :user_session
endIn 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.
Disable Authlogic validations: Update your acts_as_authenticatable configuration block to set the following flags to false:
validate_email_fieldvalidate_login_fieldvalidate_password_fieldImplement 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.
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)logincrypted_password and password_saltpersistence_token (unique index)single_access_token (unique index)perishable_token (unique index)login_count, failed_login_count, last_request_at, current_login_at, last_login_at, current_login_ipactive, approved, confirmedclass 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
endUser 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.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
endTo 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
endAuthlogic::ControllerAdapters::AbstractAdapter to Authlogic::Session::Base.controller.