Skip to main content

Authentication & OTP

Catalyst ships OTP and password sign-in flows (a Devise strategy, sessions concern, OTP model, delivery providers and views) that you opt into from the initializer.

Quick example​

config/initializers/catalyst.rb
Catalyst.configure do |config|
config.auth_method = :otp # or :password, :custom
end
rails g catalyst:add_otp_requests
rails db:migrate

Then update the User model, sessions controller and routes as described in Setup.

Setup​

1. Choose the auth method in the initializer​

# config/initializers/catalyst.rb
Catalyst.configure do |config|
config.auth_method = :otp # or :password, :custom
# ...other config
end

The gem registers its CatalystAuthenticatable Devise strategy and model module itself via ActiveSupport::Reloader.to_prepare, for every auth method other than :custom (where the host app provides its own). Registration is inert unless the user model declares devise :catalyst_authenticatable, so apps that don't use Catalyst's sign-in are unaffected.

2. Generate the OTP requests migration​

rails g catalyst:add_otp_requests
rails db:migrate

This creates the otp_requests table with columns: otp, email (citext), expired_at, status, verified_at, user_id (optional foreign key), and timestamps. An index is added on email.

3. Update the User model​

Add has_many :otp_requests to your User model:

class User < ApplicationRecord
has_many :otp_requests, dependent: :destroy, class_name: "Catalyst::OtpRequest"

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :catalyst_authenticatable

def can_access_admin_panel?
true # or your own authorization logic
end
end

The sign-in flow runs on Catalyst::OtpRequest's class methods, which you can use for custom flows (invitations, signup verification, …) too:

  • Catalyst::OtpRequest.generate!(user:, delivery_channel:) β€” generates a 6-digit OTP, creates the request, delivers it, and cancels any previous active requests. Pass email: instead of user: for flows without a user record. Raises ActiveRecord::RecordInvalid when the resend limit is hit.
  • Catalyst::OtpRequest.verify?(user:, otp:) β€” validates the OTP against the latest active request. Accepts email: instead of user: for email-only flows.

4. Configure the sessions controller​

The gem provides an OtpSessions concern that handles validate_email, validate_credentials, validate_otp, validate_password, resend_otp, and sign_in_with_credentials. Include it in your app's sessions controller:

# app/controllers/users/sessions_controller.rb
module Users
class SessionsController < Devise::SessionsController
layout 'ct_session'
helper Catalyst::ViewHelpers

include Catalyst::Admin::OtpSessions

# Add any custom actions or overrides here
# e.g. reset_password_email, send_reset_password_email, update_password
end
end

The concern provides after_successful_sign_in and after_sign_in_redirect_path as extension points for host apps to customize post-login behavior.

5. Configure routes​

# config/routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {
sessions: 'users/sessions',
passwords: 'users/passwords'
}

devise_scope :user do
post 'validate_email', to: 'users/sessions#validate_email'
get 'sign_in_with_credentials', to: 'users/sessions#sign_in_with_credentials'
post 'validate_credentials', to: 'users/sessions#validate_credentials'
get 'resend_otp', to: 'users/sessions#resend_otp'
get 'reset_password_email', to: 'users/sessions#reset_password_email'
post 'send_reset_password_email', to: 'users/sessions#send_reset_password_email'
post 'update_password', to: 'users/sessions#update_password'
end

mount Catalyst::Engine => '/cm_admin'
end

How it works​

Devise Strategy​

The CatalystAuthenticatable strategy (lib/devise/strategies/catalyst_authenticatable.rb) intercepts the validate_email action:

  1. Extracts the identifier from params (supports both identifier and legacy email param names)
  2. Calls Catalyst.config.user_lookup to find the user
  3. Checks can_access_admin_panel? on the user
  4. On success:
    • For :otp β€” creates an OTP request (sends the code) and redirects to sign_in_with_credentials
    • For :password β€” redirects to sign_in_with_credentials (password entry page)
    • For :custom β€” calls super(user) to sign in directly
  5. On failure β€” returns a generic error message

OTP Model​

Catalyst::OtpRequest (app/models/catalyst/otp_request.rb) manages OTP lifecycle:

  • Statuses: created, verified, resent, time_out, cancelled
  • Expiry: 15 minutes (scoped via active and timed_out)
  • Rate limiting: Max 5 OTP requests per 30 seconds per user or email
  • Delivery: after_create callback calls Catalyst.send_otp or Catalyst.send_otp_email

Delivery Providers​

  • Catalyst::DeliveryProviders::Email β€” sends OTP via Catalyst.send_email using the catalyst/mailers/otp/otp_email partial
  • Catalyst::DeliveryProviders::Gupshup β€” sends OTP via Gupshup WhatsApp API using configured templates

The Catalyst.send_otp method routes to the appropriate provider(s) based on otp_delivery_channel config.

Options​

The auth system supports three methods configured via Catalyst.config.auth_method:

MethodFlow
:otpUser enters email or phone β†’ receives OTP β†’ enters OTP to sign in
:passwordUser enters email or phone β†’ enters password to sign in
:customHost app provides its own flow β€” the Devise strategy signs the user in directly

OTP delivery can go through email, phone (WhatsApp via Gupshup), or both. See Configuration for all config options.

Views​

The gem provides these view templates:

  • app/views/users/sessions/new.html.slim β€” login form (identifier input)
  • app/views/users/sessions/sign_in_with_credentials.html.slim β€” OTP/password entry
  • app/views/users/sessions/_otp_sign_in.html.slim β€” OTP input partial
  • app/views/users/sessions/_password_sign_in.html.slim β€” password input partial
  • app/views/catalyst/mailers/otp/_otp_email.html.slim β€” OTP email template

Host apps can override any of these by creating files at the same paths in the host app's app/views/ directory.

Recipes​

Send OTPs over WhatsApp (phone)​

To deliver OTPs via phone (e.g. WhatsApp through Gupshup):

1. Configure delivery channel and provider​

Catalyst.configure do |config|
config.auth_method = :otp
config.otp_delivery_channel = :phone_or_email # or :phone
config.otp_delivery_provider = :gupshup
end

When otp_delivery_channel is :phone_or_email, the login screen shows a toggle that lets the user switch between phone-based and email-based login:

  • The form shows a mobile number field (with the country-code selector used across Catalyst) by default.
  • A "Use email instead" link (styled like the "Forgot Password?" link) toggles to an email field; the link then becomes "Use phone instead" to switch back. The user can toggle between the two at any time before submitting.
  • OTP delivery follows the chosen identifier β€” a phone number sends the OTP via the configured phone provider only, and an email sends it via email only. This is handled automatically by the Devise strategy and OtpSessions concern based on whether the identifier contains @.

2. Add Gupshup credentials​

# config/credentials.yml.enc or rails credentials:edit
gupshup:
api_key: "your_api_key"
source_number: "your_sender_number"
templates:
otp: "your_gupshup_template_id"

3. Ensure User model has phone_number​

The Gupshup provider calls user.phone_number β€” your User model must have a phone_number attribute.

Custom delivery providers​

Pass any object that responds to #deliver(user:, otp:, template:):

class MySmsProvider
def deliver(user:, otp:, template:)
# your SMS sending logic
end
end

config.otp_delivery_provider = MySmsProvider.new

Custom user model​

By default Catalyst uses the User model for authentication lookups, mentions, support tickets, and the history page. Override user_class with the model name or class:

config.user_class = 'AdminUser'
# or
config.user_class = AdminUser

user_class is lazily constantized, so it can be set before the model is loaded or after a Rails code reload.

Custom user lookup​

The default user_lookup lambda resolves users against config.user_class by email first, then by phone number (trailing digits match). Override it for custom logic:

config.user_lookup = lambda { |identifier|
AdminUser.find_by(email: identifier.downcase) ||
AdminUser.find_by(phone_number: identifier.gsub(/\D/, ''))
}

The lambda receives the raw identifier string from the login form (which accepts email or phone) and should return a User instance or nil.

Migrating from host-app files​

If your host app previously had its own copies of these files, you can remove them β€” the gem registers its own. When upgrading to Catalyst 10, the catalyst:upgrade codemod removes items 1–3 itself; the rest remain manual.

Files to remove from the host app​

  1. lib/devise/strategies/catalyst_authenticatable.rb β€” The gem now provides this at lib/devise/strategies/catalyst_authenticatable.rb, registered by the gem's engine.

  2. lib/devise/models/catalyst_authenticatable.rb β€” The gem provides this at lib/devise/models/catalyst_authenticatable.rb.

  3. Devise module registration in config/initializers/devise.rb β€” Remove the manual Devise.add_module(:catalyst_authenticatable, ...) block. The gem's engine initializer handles this automatically.

  4. OTP methods from User model concern β€” If your User model had inline create_otp_request, verify_otp?, etc. (e.g. in an Auth::User concern), or an include OtpAuthenticatable line from the v9 setup, delete them β€” the concern is removed in Catalyst 10. Custom callers move to Catalyst::OtpRequest.generate! and Catalyst::OtpRequest.verify?.

  5. Session controller actions β€” If your Users::SessionsController had validate_email, validate_credentials, validate_otp, resend_otp, sign_in_with_credentials methods, replace them with include Catalyst::Admin::OtpSessions. Keep only host-app-specific actions like reset_password_email, send_reset_password_email, update_password.

What stays in the host app​

  • Users::SessionsController β€” slim controller that includes Catalyst::OtpSessions and adds password reset actions
  • Users::PasswordsController β€” Devise password reset controller (the gem doesn't provide this)
  • Routes β€” the devise scope routes must remain in the host app's config/routes.rb
  • User model β€” must declare devise :catalyst_authenticatable and has_many :otp_requests, class_name: "Catalyst::OtpRequest"