Veri: Minimal Authentication for Rails
Veri is a cookie-based authentication library for Ruby on Rails. It provides only essential building blocks for secure user authentication without cluttering your app with generated controllers, views, and mailers. This makes it ideal for building custom authentication flows.
Veri supports multi-tenancy, granular session management, multiple password hashing algorithms, and provides a user impersonation feature for administration purposes.
Example of Usage:
Consider a multi-tenant SaaS application where users need to manage their active sessions across devices and browsers, terminating specific sessions remotely when needed. Administrators require similar capabilities in their admin panel, with additional powers to suspend accounts and temporarily assume user identities for troubleshooting. You can build all this easily with Veri.
Table of Contents
Gem Usage:
Community Resources:
Installation
Add Veri to your Gemfile:
gem "veri"
Install the gem:
bundle install
Generate the migration for your user model (replace users with your table name if different):
rails generate veri:authentication users
Veri's sessions table uses the same primary key type as your users table, so the table must exist before you run the generator.
If your database can't handle your UUIDs on its own, apply your app's UUID handling to Veri's session model in an initializer. The examples below show which attributes need it; the code itself depends on how your app handles UUIDs. If your app generates UUIDs:
Rails.application.config.to_prepare do
Veri::Session.before_create { self.id ||= SecureRandom.uuid }
end
If it also stores them as binary, add your binary type on top of that:
Rails.application.config.to_prepare do
Veri::Session.before_create { self.id ||= SecureRandom.uuid }
[:id, :authenticatable_id, :original_authenticatable_id, :tenant_id, :original_tenant_id].each do |name|
Veri::Session.attribute name, YourBinaryUuidType.new
end
end
If your app sets any other kind of id itself, such as its own integer ids, do the same with your own id handling.
Run the migration:
rails db:migrate
Configuration
Configure Veri in an initializer if customization is needed:
# These are the default values; you can change them as needed
Veri.configure do |config|
# Password hashing algorithm (:argon2, :bcrypt, :pbkdf2, or :scrypt)
config.hashing_algorithm = :argon2
# Session inactivity timeout (nil means sessions never expire due to inactivity)
config.inactive_session_lifetime = nil
# Maximum session duration regardless of activity
config.total_session_lifetime = 14.days
# Your user model name
config.user_model_name = "User"
end
Password Management
Your user model is automatically extended with password management methods:
# Set or update a password
user.update_password("password")
# Verify a password
user.verify_password("password")
# Check if a password is set
user.password_set?
Updating a password terminates all of the user's sessions, including the current one. To keep the user signed in, log them in again or opt out of session termination:
# Update a password and keep the user signed in
user.update_password(new_password)
log_in(user)
# Update a password without terminating sessions
user.update_password(new_password, terminate_sessions: false)
The hashing algorithm can be changed at any time: existing passwords are verified with the algorithm they were hashed with and are automatically re-hashed with the configured algorithm on the next successful login.
Controller Integration
Setup
Include the authentication module in your controllers and configure protection:
class ApplicationController < ActionController::Base
include Veri::Authentication
# Require authentication by default
with_authentication
end
class PicturesController < ApplicationController
# Allow public access to index and show actions
skip_authentication only: [:index, :show]
end
Both with_authentication and skip_authentication work exactly the same as Rails' before_action and skip_before_action methods.
Authentication Methods
This is a simplified example of how to use Veri's authentication methods:
class RegistrationsController < ApplicationController
skip_authentication
def create
user = User.new(user_params)
if user.valid?
user.update_password(user_params[:password])
log_in(user)
redirect_to dashboard_path
else
render :new, status: :unprocessable_content
end
end
end
class SessionsController < ApplicationController
skip_authentication except: [:destroy]
def create
user = User.find_by(email: params[:email])
if user&.verify_password(params[:password])
log_in(user)
redirect_to return_path || dashboard_path
else
flash.now[:alert] = "Invalid credentials"
render :new, status: :unprocessable_content
end
end
def destroy
log_out
redirect_to root_path
end
end
Available controller methods:
# Returns authenticated user or nil
current_user
# Returns true if user is authenticated
logged_in?
# Authenticates user, returns true on success or false if account is suspended
log_in(user)
# Terminates current session
log_out
# Returns path user was trying to access before authentication, if any
return_path
# Returns current authentication session
current_session
When Unauthenticated
By default, when unauthenticated, Veri redirects back (HTML) or returns 401 (other formats). Override this private method to customize behavior for unauthenticated users:
class ApplicationController < ActionController::Base
include Veri::Authentication
with_authentication
private
def when_unauthenticated
redirect_to login_path
end
end
Authentication Sessions
Veri stores authentication sessions in the database, providing session management capabilities:
Session Access
# Get all sessions for a user
user.sessions
# Get current session in controller
current_session
# Get session from a request
Veri::Session.from_request(request)
Sessions Outside Controllers
Code that handles a request outside of controllers, such as Action Cable connections and route constraints, can find the current session from the request:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
# Runs only when the connection opens; disconnecting it after the session is terminated is up to your application
def connect
self.current_user = Veri::Session.from_request(request)&.identity || reject_unauthorized_connection
end
end
end
# Only administrators can open the jobs dashboard
constraints -> (request) { Veri::Session.from_request(request)&.identity&.admin? } do
mount Sidekiq::Web => "/jobs"
end
Session Information
# Get the authenticated user
session.identity
# Get session details
session.info
# => {
# device: "Desktop",
# os: "macOS",
# browser: "Chrome",
# ip_address: "1.2.3.4",
# last_seen_at: "2023-10-01 12:00:00"
# }
Session Status
# Session is active (neither expired nor inactive)
session.active?
# Session exceeded inactivity timeout
session.inactive?
# Session exceeded maximum lifetime
session.expired?
# Fetch active sessions
Veri::Session.active
# Fetch inactive sessions
Veri::Session.inactive
# Fetch expired sessions
Veri::Session.expired
Session Management
# Terminate a specific session
session.terminate
# Terminate all sessions
Veri::Session.terminate_all
# Terminate all sessions for a specific user
user.sessions.terminate_all
# Clean up inactive sessions for a specific user
user.sessions.inactive.terminate_all
# Clean up expired sessions globally
Veri::Session.expired.terminate_all
When the current session is terminated, the controller still sees it for the rest of the request, so logged_in? stays true until the next request unless you call log_in or log_out. The same applies when a password update or an account suspension terminates it.
Account Suspension
Veri provides account suspension functionality to temporarily disable user accounts.
# Suspend a user account
user.suspend!
# Unsuspend a user account
user.unsuspend!
# Check if account is suspended
user.suspended?
# Fetch suspended users
User.suspended
# Fetch unsuspended users
User.unsuspended
When an account is suspended, the user cannot log in. If they're already logged in, their sessions are terminated and they are treated as unauthenticated.
User Impersonation
Veri provides user impersonation functionality that allows administrators to temporarily assume another user's identity:
module Admin
class ImpersonationController < ApplicationController
def create
user = User.find(params[:user_id])
current_session.shapeshift(user)
redirect_to root_path, notice: "Now viewing as #{user.name}"
end
def destroy
original_user = current_session.true_identity
current_session.to_true_identity
redirect_to admin_dashboard_path, notice: "Returned to #{original_user.name}"
end
end
end
Available session methods:
# Assume another user's identity (in single-tenant applications)
session.shapeshift(user)
# Return to original identity
session.to_true_identity
# Returns true if currently shapeshifted
session.shapeshifted?
# Returns original user when shapeshifted, otherwise current user
session.true_identity
# Fetch the sessions in which someone is impersonating this user
user.sessions.shapeshifted
User method:
# Returns the sessions in which a user is impersonating someone
user.shapeshifter_sessions
Controller helper:
# Returns true if the current session is shapeshifted
shapeshifter?
Multi-Tenancy
Veri supports multi-tenancy, allowing you to tie authentication sessions to tenants such as organizations, clients, or subdomains.
Setup
Pass the tenant when logging a user in:
# Option 1: String-based tenancy (e.g., subdomain)
log_in(user, tenant: request.subdomain)
# Option 2: Model-based tenancy (e.g., organization)
log_in(user, tenant: company)
Tenants can be represented as either a string or an instance of a model declared as a tenant:
class Company < ApplicationRecord
veri_tenant
end
Without the tenant: argument the session has no tenant, which is the single-tenant setup.
Use current_tenant in controllers and views to get the tenant of the current session:
# Returns the tenant (string, model instance, or nil if the session has no tenant)
current_tenant
Since nil is a valid tenant, current_tenant raises an error when no user is logged in.
Veri only stores the tenant in the session and returns it. The session itself is found by its cookie alone, whatever its tenant. How your application uses the tenant, if at all, is entirely up to it, so tenant management and scoping are the application's responsibility.
Session Tenant Access
Sessions expose their tenant through the tenant method:
# Returns the tenant (string, model instance, or nil in single-tenant applications)
session.tenant
To manage sessions for a specific tenant:
# Fetch all sessions for a given tenant
Veri::Session.in_tenant(tenant)
# Fetch sessions for a specific user within a tenant
user.sessions.in_tenant(tenant)
# Terminate all sessions for a specific user within a tenant
user.sessions.in_tenant(tenant).terminate_all
# If you use impersonation, fetch a user's impersonating sessions that return to a given tenant
user.shapeshifter_sessions.in_original_tenant(tenant)
Switching Tenants
A session belongs to one tenant, and a browser holds one session per host. A user is therefore logged in to one tenant at a time, unless your tenants live on separate subdomains, where each subdomain keeps its own session.
To move a user to another tenant, call switch_tenant on their session:
class CompaniesController < ApplicationController
def switch
company = current_user.companies.find(params[:id])
current_session.switch_tenant(company)
redirect_to root_path, notice: "Switched to #{company.name}"
end
end
The user stays logged in and the session keeps its expiration. This also covers applications where the tenant is not known at login: log the user in without a tenant and switch once they choose one.
User Impersonation with Tenants
When using user impersonation in a multi-tenant setup, Veri allows cross-tenant shapeshifting while preserving the original tenant context:
# Assume another user's identity across tenants
session.shapeshift(user, tenant: company)
# Returns the original tenant when shapeshifted
session.true_tenant
The tenant: argument always becomes the session's tenant: omitting it means no tenant. In a multi-tenant application, always pass it explicitly.
All other session methods work the same way in multi-tenant applications as in single-tenant applications. However, to_true_identity will restore both the original user and tenant.
Orphaned Sessions
Destroying a record of a model declared with veri_tenant also deletes its sessions, including the impersonating sessions that return to it, so their users are logged out.
Sessions become orphaned when their tenant is removed without running Active Record callbacks, for example with delete or raw SQL, or is destroyed after its model stopped declaring veri_tenant. Users with orphaned sessions remain logged in, and looking up their tenant raises an error. Use prune as a fallback to delete orphaned sessions:
Veri::Session.prune
Tenant Migrations