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β
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. Passemail:instead ofuser:for flows without a user record. RaisesActiveRecord::RecordInvalidwhen the resend limit is hit.Catalyst::OtpRequest.verify?(user:, otp:)β validates the OTP against the latest active request. Acceptsemail:instead ofuser: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:
- Extracts the
identifierfrom params (supports bothidentifierand legacyemailparam names) - Calls
Catalyst.config.user_lookupto find the user - Checks
can_access_admin_panel?on the user - On success:
- For
:otpβ creates an OTP request (sends the code) and redirects tosign_in_with_credentials - For
:passwordβ redirects tosign_in_with_credentials(password entry page) - For
:customβ callssuper(user)to sign in directly
- For
- 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
activeandtimed_out) - Rate limiting: Max 5 OTP requests per 30 seconds per user or email
- Delivery:
after_createcallback callsCatalyst.send_otporCatalyst.send_otp_email
Delivery Providersβ
Catalyst::DeliveryProviders::Emailβ sends OTP viaCatalyst.send_emailusing thecatalyst/mailers/otp/otp_emailpartialCatalyst::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:
| Method | Flow |
|---|---|
:otp | User enters email or phone β receives OTP β enters OTP to sign in |
:password | User enters email or phone β enters password to sign in |
:custom | Host 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 entryapp/views/users/sessions/_otp_sign_in.html.slimβ OTP input partialapp/views/users/sessions/_password_sign_in.html.slimβ password input partialapp/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
OtpSessionsconcern 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β
-
lib/devise/strategies/catalyst_authenticatable.rbβ The gem now provides this atlib/devise/strategies/catalyst_authenticatable.rb, registered by the gem's engine. -
lib/devise/models/catalyst_authenticatable.rbβ The gem provides this atlib/devise/models/catalyst_authenticatable.rb. -
Devise module registration in
config/initializers/devise.rbβ Remove the manualDevise.add_module(:catalyst_authenticatable, ...)block. The gem's engine initializer handles this automatically. -
OTP methods from User model concern β If your User model had inline
create_otp_request,verify_otp?, etc. (e.g. in anAuth::Userconcern), or aninclude OtpAuthenticatableline from the v9 setup, delete them β the concern is removed in Catalyst 10. Custom callers move toCatalyst::OtpRequest.generate!andCatalyst::OtpRequest.verify?. -
Session controller actions β If your
Users::SessionsControllerhadvalidate_email,validate_credentials,validate_otp,resend_otp,sign_in_with_credentialsmethods, replace them withinclude Catalyst::Admin::OtpSessions. Keep only host-app-specific actions likereset_password_email,send_reset_password_email,update_password.
What stays in the host appβ
Users::SessionsControllerβ slim controller that includesCatalyst::OtpSessionsand adds password reset actionsUsers::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 Usermodel β must declaredevise :catalyst_authenticatableandhas_many :otp_requests, class_name: "Catalyst::OtpRequest"