Agent skill
rails-auth-patterns
Authentication patterns for Rails applications. Automatically invoked when working with user login, signup, sessions, password resets, token authentication, has_secure_password, Devise, or auth configuration. Triggers on "authentication", "auth", "login", "signup", "session", "password", "has_secure_password", "Devise", "current_user", "sign_in", "sign_out", "remember me", "password reset", "email confirmation". NOT for authorization/permissions (use controller patterns for Pundit) or API token auth (use rails-api-patterns for JWT).
Install this agent skill to your Project
npx add-skill https://github.com/ag0os/rails-dev-plugin/tree/main/skills/rails-auth-patterns
SKILL.md
Rails Authentication Patterns
Profile-aware authentication guidance. Never suggest replacing one approach with another unless explicitly asked.
See patterns.md for detailed code examples.
Profile Detection
Check the project before recommending:
1. grep "devise" Gemfile → Devise (service-oriented)
2. grep "has_secure_password" app/models/ → Built-in auth (omakase)
3. Check for app/controllers/sessions_controller.rb → Custom auth
4. Rails 8+? → Built-in generator available
| Approach | Profile | Use When |
|---|---|---|
| Rails 8 generator | Omakase (Rails 8+) | New projects, full control, no gem dependencies |
has_secure_password (manual) |
Omakase (pre-8) | Simple auth, full control |
| Devise | Service-oriented | Multi-feature auth (confirmable, lockable, omniauthable) |
Rails 8 Built-In Auth
What the Generator Creates
bin/rails generate authentication
# Creates: User model, Session model, SessionsController,
# Authentication concern, PasswordsController, PasswordsMailer, migrations
Key Rails 8 Features (Non-Obvious)
generates_token_for with automatic invalidation:
class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
normalizes :email_address, with: -> { _1.strip.downcase }
# Token auto-invalidates when password_salt changes (i.e., password changed)
generates_token_for :password_reset, expires_in: 15.minutes do
password_salt&.last(10)
end
# Token auto-invalidates when email changes
generates_token_for :email_confirmation, expires_in: 24.hours do
email_address
end
# Non-expiring token (e.g., unsubscribe links)
generates_token_for :unsubscribe
end
# Generate: user.generate_token_for(:password_reset)
# Find: User.find_by_token_for(:password_reset, token) # nil if expired/invalid
# Find!: User.find_by_token_for!(:password_reset, token) # raises if invalid
CurrentAttributes pattern:
# app/models/current.rb
class Current < ActiveSupport::CurrentAttributes
attribute :session
delegate :user, to: :session, allow_nil: true
end
Rate limiting (Rails 8 built-in):
class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[new create]
rate_limit to: 10, within: 3.minutes, only: :create, with: -> {
redirect_to new_session_url, alert: "Try again later."
}
end
class PasswordsController < ApplicationController
rate_limit to: 5, within: 1.hour, only: :create, with: -> {
redirect_to new_password_url, alert: "Too many reset requests."
}
end
Multiple session management:
# Allow users to see/terminate their active sessions
def destroy_all
Current.user.sessions.where.not(id: Current.session.id).destroy_all
redirect_to sessions_path, notice: "All other sessions terminated."
end
Devise — Key Customization Points
Follow standard Devise setup/installation docs. The non-obvious parts:
Turbo compatibility (Rails 7+) — required:
# config/initializers/devise.rb
config.responder.error_status = :unprocessable_entity
config.responder.redirect_status = :see_other
config.navigational_formats = ["*/*", :html, :turbo_stream]
Custom failure app for Turbo (if redirects break):
class TurboFailureApp < Devise::FailureApp
def respond
if request_format == :turbo_stream
redirect
else
super
end
end
def skip_format?
%w[html turbo_stream */*].include?(request_format.to_s)
end
end
# config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = TurboFailureApp
end
See patterns.md for OmniAuth integration and custom controller patterns.
Profile-Aware Test Helpers
Omakase (Minitest):
class SessionsControllerTest < ActionDispatch::IntegrationTest
test "login with valid credentials" do
user = users(:jane)
post session_url, params: { email_address: user.email_address, password: "password" }
assert_redirected_to root_path
end
test "rate limiting after 10 attempts" do
11.times { post session_url, params: { email_address: "x@x.com", password: "wrong" } }
assert_redirected_to new_session_url
follow_redirect!
assert_match "Try again later", flash[:alert]
end
end
Service-oriented (RSpec + Devise):
# spec/rails_helper.rb
RSpec.configure do |config|
config.include Devise::Test::IntegrationHelpers, type: :request
config.include Devise::Test::IntegrationHelpers, type: :system
end
# In specs — use sign_in helper, don't hit the login endpoint
before { sign_in user }
Anti-Patterns
| Anti-Pattern | Problem | Fix |
|---|---|---|
| No rate limiting on login | Brute force attacks | rate_limit (Rails 8) or Rack::Attack |
| Password reset tokens without expiry | Token reuse attacks | expires_in: 15.minutes |
| Leaking user existence on reset | Enumeration attacks | Same response for valid/invalid emails |
| Session fixation | Hijacking | reset_session on login |
| Rolling your own token system | Crypto bugs | Use generates_token_for or Devise tokens |
Output Format
When implementing auth, provide:
- Model with auth configuration
- Controller(s) for sessions, registrations, password resets
- Routes configuration
- Test file matching project profile (Minitest or RSpec)
- Security notes (rate limiting, token expiry, session management)
Recommended Agent Skills
Expand your agent's capabilities with these related and highly-rated skills.
rails-caching-patterns
Caching patterns for Rails applications including fragment caching, low-level caching, HTTP caching, Russian doll caching, and cache invalidation strategies. Automatically invoked when working with Rails.cache, cache stores, stale?/fresh_when, fragment caching, cache keys, or performance optimization through caching. Triggers on "cache", "caching", "Rails.cache", "fragment cache", "Russian doll", "stale?", "fresh_when", "cache key", "cache store", "Redis cache", "Solid Cache", "memcached", "ETag", "cache invalidation", "cache bust". NOT for CDN configuration (use rails-devops-patterns) or database query optimization (use rails-model-patterns).
rails-graphql-patterns
Analyzes and recommends GraphQL patterns for Rails using graphql-ruby including schema design, types, resolvers, mutations, subscriptions, DataLoader, and query complexity. Use when building GraphQL APIs, defining types, writing mutations, optimizing N+1 queries, or structuring app/graphql. NOT for REST API controllers, ActiveRecord queries outside GraphQL, or Turbo Stream responses.
ruby-object-design
Automatically invoked when making decisions about Ruby code structure and organization. Triggers on "class or module", "should this be a class", "struct vs class", "PORO", "data object", "design pattern", "class vs module", "when to use class", "module vs class", "stateless class", "value object", "data container", "object factory", "extend self", "singleton class". Provides guidance on choosing the right Ruby construct (class, module, Struct, Data, Hash). NOT for code smell identification or refactoring (use ruby-refactoring) or Rails-specific framework patterns.
rails-views-patterns
Analyzes Rails view templates, partials, layouts, helpers, and form patterns for best practices. Use when reviewing ERB templates, improving view performance with fragment caching, fixing form helpers, organizing partials, adding accessibility attributes, or evaluating collection rendering. NOT for Stimulus/Turbo logic (use hotwire-patterns), controller concerns, or API-only responses.
rails-architecture-patterns
Provides architectural planning, design decisions, and coordination guidance for Rails applications. Use when planning new features, choosing between design approaches (STI vs polymorphic, service vs concern, monolith vs engine), evaluating system architecture, or deciding which domain skill or agent to delegate to. NOT for implementation details within a single domain (use the domain-specific skill instead).
rails-mailer-patterns
Action Mailer patterns for Rails applications. Automatically invoked when working with email delivery, mailer classes, email templates, mailer previews, interceptors, or delivery configuration. Triggers on "mailer", "email", "ActionMailer", "deliver_later", "deliver_now", "mail template", "email preview", "SMTP", "SendGrid", "Postmark", "notification email". NOT for push notifications, SMS, or in-app messaging.
Didn't find tool you were looking for?