Implement database-backed session management with cookie handling, audit trails, and multiple device support. Use when building authentication systems that need session tracking, device management, or security audit capabilities.
Database-backed session management for Rails with audit trails, multi-device support, and session revocation.
| Feature | Cookie-Only | Database-Backed |
|---|---|---|
| Session revocation | No | Yes |
| "Sign out everywhere" | No | Yes |
| Audit trail | No | Yes |
| Multiple device view | No | Yes |
| API token support |
| Limited |
| Full |
# app/models/session.rb
class Session < ApplicationRecord
belongs_to :user
scope :active, -> { where('created_at > ?', 30.days.ago) }
scope :recent, -> { order(created_at: :desc) }
end
class CreateSessions < ActiveRecord::Migration[8.0]
def change
create_table :sessions, id: :uuid do |t|
t.references :user, null: false, foreign_key: true, type: :uuid
t.string :ip_address
t.string :user_agent
t.timestamps
end
end
end
# app/controllers/concerns/authentication.rb
module Authentication
extend ActiveSupport::Concern
included do
before_action :require_authentication
end
private
def require_authentication
resume_session || request_authentication
end
def resume_session
Current.session ||= find_session_by_cookie
end
def find_session_by_cookie
Session.find_by(id: cookies.signed[:session_id])
end
def start_new_session_for(user)
user.sessions.create!(
user_agent: request.user_agent,
ip_address: request.remote_ip
).tap do |session|
Current.session = session
cookies.signed.permanent[:session_id] = {
value: session.id,
httponly: true,
same_site: :lax
}
end
end
def terminate_session
Current.session.destroy
cookies.delete(:session_id)
end
end
signed - Cryptographically signed, tamper-proofpermanent - 20-year expiryhttponly: true - XSS protectionsame_site: :lax - CSRF protectionFor complete implementation details: