### Manual Installation: Add Gem and Migrations Source: https://github.com/kobaltz/action_auth/blob/main/README.md For manual installation, add the gem to your Gemfile and then run the command to install migrations. ```ruby bundle add action_auth bin/rails action_auth:install:migrations ``` -------------------------------- ### Install ActionAuth Gem and Mount Engine Source: https://context7.com/kobaltz/action_auth/llms.txt Add the ActionAuth gem to your Gemfile, install it, and mount the engine in your application's routes. ```ruby gem "action_auth" gem "bcrypt", "~> 3.1" # Optional additions: # gem "pwned" # Have I Been Pwned integration # gem "webauthn" # WebAuthn / passkey support ``` ```bash bundle install bin/rails action_auth:install # copies migrations, generates config/initializers/action_auth.rb ``` ```ruby Rails.application.routes.draw do mount ActionAuth::Engine => "action_auth" root "dashboard#index" end ``` -------------------------------- ### Install ActionAuth with Rake Task Source: https://github.com/kobaltz/action_auth/blob/main/README.md Run this command after adding the gem to your Gemfile to install ActionAuth, copying over migrations, config, and routes. ```bash bin/rails action_auth:install ``` -------------------------------- ### Rails Routes with Constraints Source: https://context7.com/kobaltz/action_auth/llms.txt Example of mounting ActionAuth engine and applying route constraints for authenticated and admin users. ```ruby # config/routes.rb Rails.application.routes.draw do mount ActionAuth::Engine => "action_auth" constraints AuthenticatedConstraint do root to: "dashboard#index" end root to: "welcome#index" constraints AdminConstraint do mount GoodJob::Engine => "good_job" end end ``` -------------------------------- ### User Registration Form Source: https://context7.com/kobaltz/action_auth/llms.txt Example of a new user registration form using form_with. Ensure password fields meet the minimum length and complexity requirements. ```erb <%# app/views/action_auth/registrations/new.html.erb (override example) %> <%= form_with url: sign_up_path do |form| %> <%= form.email_field :email, required: true, autocomplete: "email" %> <%= form.password_field :password, required: true, autocomplete: "new-password", placeholder: "Min 12 chars, upper+lower+digit+special" %> <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password" %> <%= form.submit "Sign Up" %> <% end %> ``` -------------------------------- ### Add Delete Account Button Source: https://github.com/kobaltz/action_auth/blob/main/README.md Example of how to add a button to initiate account deletion. This should be styled to fit your application and include a confirmation dialog. ```html

Unhappy with the service? <%= button_to "Delete Account", action_auth.users_path, method: :delete %>

``` -------------------------------- ### Configure Action Auth Settings Source: https://github.com/kobaltz/action_auth/blob/main/README.md Customize Action Auth behavior by enabling password complexity checks and setting session timeouts. Ensure all necessary configurations are applied during application setup. ```ruby ActionAuth.configure do |config| # Enable password complexity validation config.password_complexity_check = true # Set session timeout (defaults to 2 weeks) config.session_timeout = 2.weeks # Other settings as needed... end ``` -------------------------------- ### Customized Application Layout with TailwindCSS Source: https://github.com/kobaltz/action_auth/wiki/Overriding-Sign-In-page-view An example of a customized layout file that integrates with an application's existing stylesheets and applies TailwindCSS classes. Ensure you keep Action Auth's JavaScript and meta tags for WebAuthn. ```erb example <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "application", media: "all" %> <%= javascript_include_tag "action_auth/application", "data-turbo-track": "reload", type: "module" %> <% if ActionAuth.configuration.webauthn_enabled? %> <%= tag :meta, name: :webauthn_auth_url, content: action_auth.webauthn_credential_authentications_url %> <%= tag :meta, name: :webauthn_cred_url, content: action_auth.webauthn_credentials_url %> <%= tag :meta, name: :webauthn_redirect_url, content: action_auth.sessions_url %> <% end %> <%= yield %> <%= yield(:cancel_path) %> ``` -------------------------------- ### Email Verification - Ruby Source: https://context7.com/kobaltz/action_auth/llms.txt Provides Ruby code for manually resending a verification email and outlines the automatic token verification process via a GET request. ```ruby # Resend verification email manually (e.g., from a support script): user = ActionAuth::User.find_by(email: "user@example.com") ActionAuth::UserMailer.with(user: user).email_verification.deliver_later # Token verification happens automatically via the engine route: # GET /action_auth/identity/email_verification?sid= # => user.update!(verified: true) # => redirect to sign_in_path with notice # POST /action_auth/identity/email_verification params: { email: } # => Finds user by email and re-sends verification email ``` -------------------------------- ### Set up User Model Source: https://github.com/kobaltz/action_auth/blob/main/README.md Inherit your User model from `ActionAuth::User` to integrate with ActionAuth. This allows for custom associations like `has_many :posts`. ```ruby # app/models/user.rb class User < ActionAuth::User has_many :posts, dependent: :destroy end ``` -------------------------------- ### Configure WebAuthn Settings Source: https://github.com/kobaltz/action_auth/blob/main/README.md Enable WebAuthn and configure its settings, including the origin URL and relying party name. Ensure the origin name does not have a trailing slash or port number. ```ruby ActionAuth.configure do |config| config.webauthn_enabled = true config.webauthn_origin = "http://localhost:3000" # or "https://example.com" config.webauthn_rp_name = Rails.application.class.to_s.deconstantize config.verify_email_on_sign_in = true config.default_from_email = "from@example.com" end ``` -------------------------------- ### Configure WebAuthn / Passkeys Source: https://context7.com/kobaltz/action_auth/llms.txt Enables WebAuthn/Passkey authentication and configures essential settings like the origin URL and relying party name. Set `passkey_only` to true to allow sign-in without email or password. ```ruby # config/initializers/action_auth.rb ActionAuth.configure do |config| config.webauthn_enabled = true config.webauthn_origin = "https://myapp.com" # must match browser origin exactly config.webauthn_rp_name = "My App" config.passkey_only = true # allow sign-in via passkey without email/password end ``` -------------------------------- ### Configure ActionAuth Settings Source: https://github.com/kobaltz/action_auth/blob/main/README.md Add these configuration settings to your `config/initializers/action_auth.rb` file to customize ActionAuth behavior. ```ruby ActionAuth.configure do |config| config.allow_user_deletion = true config.default_from_email = "from@example.com" config.magic_link_enabled = true config.passkey_only = true # Allows sign in with only a passkey config.pwned_enabled = true # defined?(Pwned) config.password_complexity_check = true # Requires complex passwords config.session_timeout = 2.weeks # Session expires after this period of inactivity config.sms_auth_enabled = false config.verify_email_on_sign_in = true config.webauthn_enabled = true # defined?(WebAuthn) config.webauthn_origin = "http://localhost:3000" # or "https://example.com" config.webauthn_rp_name = Rails.application.class.to_s.deconstantize config.insert_cookie_domain = false end ``` -------------------------------- ### Set up Current Model for User Context Source: https://github.com/kobaltz/action_auth/blob/main/README.md Define a `Current` model inheriting from `ActiveSupport::CurrentAttributes` to manage the current user context. This allows `Current.user` to resolve to your application's `User` model. ```ruby # app/models/current.rb class Current < ActiveSupport::CurrentAttributes def user return unless ActionAuth::Current.user ActionAuth::Current.user&.becomes(User) end end ``` -------------------------------- ### User Sign-In Source: https://context7.com/kobaltz/action_auth/llms.txt Handles user sign-in, including email verification, second-factor authentication, and session management. ```APIDOC ## User Sign-In — `SessionsController#create` Handles `POST /action_auth/sign_in`. Rate-limited to 5 attempts per 20 seconds. Checks email verification status, second-factor (WebAuthn), and sets a permanent, signed, HttpOnly session cookie. ### POST /action_auth/sign_in **Description**: Authenticates a user with email and password. It checks for email verification, handles second-factor authentication if enabled, and establishes a secure session cookie. Redirects to the application's root path upon successful sign-in. **Parameters**: * **email** (string) - Required - The user's email address. * **password** (string) - Required - The user's password. **Response**: * **Success Response (302 Found)**: Redirects to `main_app.root_path` with a success notice. * **Error Response (401 Unauthorized or other)**: Handles authentication failures, potentially redirecting to password reset or email verification flows. ``` -------------------------------- ### Add WebAuthn Gem Source: https://github.com/kobaltz/action_auth/blob/main/README.md Add the `webauthn` gem to your application's Gemfile to enable WebAuthn functionality. This is a separate step as not all users may require this feature. ```bash bundle add webauthn ``` -------------------------------- ### Asset Integration - Host App Stylesheet Source: https://context7.com/kobaltz/action_auth/llms.txt Integrate ActionAuth assets by using the host application's stylesheet and keeping ActionAuth's JavaScript for WebAuthn. ```erb <%# Use host app stylesheet, keep ActionAuth JS %> <%= stylesheet_link_tag "application" %> <%= javascript_include_tag "action_auth/application", type: "module" %> ``` -------------------------------- ### Customized Sign-In Page with Main App Integration Source: https://github.com/kobaltz/action_auth/wiki/Overriding-Sign-In-page-view This ERB code demonstrates a more customized sign-in page, including integration with your main application's assets and routing using `main_app`. It also includes styling and links for sign-up and password reset. ```erb
<%= link_to main_app.root_path do %> <%= image_tag "logo.png", class: "h-12 w-auto sm:h-16" %> <% end %>

Sign in to your account

Don't have an account? <%= link_to "Sign up" , sign_up_path, class: "font-medium text-blue-600 hover:underline" %> today.

<%= notice %>

<%= alert %>

<%= form_with url: sign_in_path, html: { class: "mt-10 grid grid-cols-1 gap-y-8"} do |form| %>
<%= form.label :email, "Email address", class: "mb-3 block text-sm font-medium text-gray-700" %> <%= form.email_field :email, value: params[:email_hint], required: true, autofocus: true, autocomplete: "email", class: "block w-full appearance-none rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-blue-500 sm:text-sm" %>
<%= form.label :password, class: "mb-3 block text-sm font-medium text-gray-700" %> <%= form.password_field :password, required: true, autocomplete: "current-password", class: "block w-full appearance-none rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:bg-white focus:outline-none focus:ring-blue-500 sm:text-sm" %>
<%= form.submit "Sign in →".html_safe , class: "group inline-flex items-center justify-center rounded-full py-2 px-4 text-sm font-semibold focus:outline-none focus-visible:outline-2 focus-visible:outline-offset-2 bg-blue-600 text-white hover:text-slate-100 hover:bg-blue-500 active:bg-blue-800 active:text-blue-100 focus-visible:outline-blue-600 w-full" %>
<%= link_to "Reset Password" , new_identity_password_reset_path, class: "font-medium text-blue-600 hover:underline" %> | <%= link_to "Verify Email" , identity_email_verification_path, class: "font-medium text-blue-600 hover:underline" %>
<% end %>
``` -------------------------------- ### Configure Default From Email Source: https://context7.com/kobaltz/action_auth/llms.txt Configure the default 'from' email address globally for ActionAuth mailers. ```ruby ActionAuth.configure do |config| config.default_from_email = "noreply@myapp.com" end ``` -------------------------------- ### Asset Integration - Importmap CSS/JS Source: https://context7.com/kobaltz/action_auth/llms.txt If using importmap with plain CSS, add ActionAuth assets to `app/assets/config/manifest.js`. ```javascript <%# If using importmap + plain CSS, add to app/assets/config/manifest.js: %> <%# //= link action_auth/application.css %> <%# //= link action_auth/application.js %> ``` -------------------------------- ### Mount ActionAuth Engine in Routes Source: https://github.com/kobaltz/action_auth/blob/main/README.md Modify config/routes.rb to mount the ActionAuth engine. The path can be customized. ```ruby mount ActionAuth::Engine => 'action_auth' ``` -------------------------------- ### Include ActionAuth Assets Source: https://github.com/kobaltz/action_auth/blob/main/README.md If using importmaps and plain CSS, add these lines to your `app/assets/config/manifest.js` file to include ActionAuth's CSS and JavaScript. ```javascript //= link action_auth/application.css //= link action_auth/application.js ``` -------------------------------- ### Custom Sign-in View Source: https://context7.com/kobaltz/action_auth/llms.txt A minimal custom sign-in view for ActionAuth, demonstrating form submission and links to other authentication pages. Uses `main_app.*` helpers for linking back to the host application. ```erb <%# Minimal custom sign-in view — app/views/action_auth/sessions/new.html.erb %> <%= form_with url: sign_in_path do |form| %> <%= form.email_field :email, value: params[:email_hint], required: true, autocomplete: "email", class: "input" %> <%= form.password_field :password, required: true, autocomplete: "current-password", class: "input" %> <%= form.submit "Sign In", class: "btn-primary" %> <% end %> <%= link_to "Sign Up", sign_up_path %> <%= link_to "Reset Password", new_identity_password_reset_path %> <%= link_to "Resend Verification", identity_email_verification_path %> <%# Use main_app.* helpers to link back to the host application: %> <%= link_to "Home", main_app.root_path %> ``` -------------------------------- ### User Registration Source: https://context7.com/kobaltz/action_auth/llms.txt Handles user registration, including optional validation and rate-limiting. ```APIDOC ## User Registration — `RegistrationsController` Handles `GET /action_auth/sign_up` and `POST /action_auth/sign_up`. Applies registration rate-limiting (3 requests / 60 seconds) and optional Have I Been Pwned validation before saving. ### POST /action_auth/sign_up **Description**: Creates a new user account. On success, it either sends a verification email or creates a session and redirects to the sign-in path. On failure, it re-renders the new registration form with errors. **Parameters**: * **email** (string) - Required - The user's email address. * **password** (string) - Required - The user's password (minimum 12 characters). * **password_confirmation** (string) - Required - The confirmation of the user's password. **Response**: * **Success Response (302 Found)**: Redirects to `/action_auth/sign_in`. * **Error Response (422 Unprocessable Entity)**: Re-renders the registration form with validation errors. ``` -------------------------------- ### User Sign-In Flow Source: https://context7.com/kobaltz/action_auth/llms.txt Details the POST request flow for user sign-in, including authentication, second-factor checks, email verification status, and session cookie creation. ```text # POST /action_auth/sign_in params: { email:, password: } # # Flow: # 1. User.authenticate_by(email:, password:) — constant-time comparison # 2. If second_factor_enabled? => redirect to WebAuthn challenge # 3. If verify_email_on_sign_in and !user.verified? => redirect with alert # 4. Creates ActionAuth::Session, sets cookies.signed.permanent[:session_token] # 5. Redirects to main_app.root_path with notice # # Cookie attributes: # httponly: true # secure: true (production only) # same_site: :lax (non-test environments) # domain: :all (if insert_cookie_domain: true) ``` -------------------------------- ### User Authentication Paths Source: https://context7.com/kobaltz/action_auth/llms.txt Provides direct access to user authentication and registration routes. ```APIDOC ## User Authentication Paths Provides direct access to user authentication and registration routes. ### GET /action_auth/sign_in **Description**: Renders the sign-in form. ### GET /action_auth/sign_up **Description**: Renders the user registration form. ### GET /action_auth/sessions **Description**: Manages user devices and active sessions. ### DELETE /action_auth/sessions/:id **Description**: Signs out a specific user session from a device. ### GET /action_auth/password/edit **Description**: Renders the form to edit the user's password. ### PATCH /action_auth/password **Description**: Updates the user's password. ``` -------------------------------- ### User Sign-In Form Source: https://context7.com/kobaltz/action_auth/llms.txt A minimal sign-in form. It includes fields for email and password, along with links for password reset and email verification resend. ```erb <%# app/views/action_auth/sessions/new.html.erb (minimal) %> <%= form_with url: sign_in_path do |form| %> <%= form.email_field :email, value: params[:email_hint], required: true, autocomplete: "email" %> <%= form.password_field :password, required: true, autocomplete: "current-password" %> <%= form.submit "Sign In" %> <% end %> <%= link_to "Forgot password?", new_identity_password_reset_path %> <%= link_to "Resend verification", identity_email_verification_path %> ``` -------------------------------- ### Basic Sign-In Form Override Source: https://github.com/kobaltz/action_auth/wiki/Overriding-Sign-In-page-view Copy this ERB code into `app/views/action_auth/sessions/new.html.erb` to create a basic sign-in form. Ensure the form structure remains consistent. ```erb <%= form_with(url: sign_in_path) do |form| %>
<%= form.label :email, style: "display: block" %> <%= form.email_field :email, value: params[:email_hint], required: true, autofocus: true, autocomplete: "email" %>
<%= form.label :password, style: "display: block" %> <%= form.password_field :password, required: true, autocomplete: "current-password" %>
<%= form.submit "Sign in", class: "btn btn-primary" %>
<% end %>
<%= link_to "Sign Up", sign_up_path %> | <%= link_to "Reset Password", new_identity_password_reset_path %> | <%= link_to "Verify Email", identity_email_verification_path %>
``` -------------------------------- ### Add ActionAuth Gem Source: https://github.com/kobaltz/action_auth/blob/main/README.md Add this line to your application's Gemfile to include the ActionAuth gem. ```ruby bundle add action_auth ``` -------------------------------- ### Using Controller Helpers in Rails Source: https://context7.com/kobaltz/action_auth/llms.txt ActionAuth automatically includes controller helpers like `current_user`, `user_signed_in?`, and `authenticate_user!`. These can be used in your controllers and views. ```ruby class ApplicationController < ActionController::Base # Helpers are already included by the engine — nothing to add. end ``` ```ruby # Usage in any controller: class PostsController < ApplicationController before_action :authenticate_user! # redirects to sign-in if not authenticated def index @posts = current_user.posts # current_session => ActionAuth::Session record # user_signed_in? => true / false end end ``` ```erb # Usage in views: # app/views/layouts/application.html.erb # # <% if user_signed_in? %> # Signed in as <%= current_user.email %> # <%= link_to "Security", user_sessions_path %> # <%= button_to "Sign Out", user_session_path(current_session), method: :delete %> <% else %> <%= link_to "Sign In", new_user_session_path %> <%= link_to "Sign Up", new_user_registration_path %> <% end %> ``` -------------------------------- ### Configure SMS Sender Class Source: https://github.com/kobaltz/action_auth/blob/main/README.md This block configures the SMS sender class after the application has been initialized. ```ruby Rails.application.config.after_initialize do ActionAuth.configure do |config| config.sms_send_class = SmsSender end end ``` -------------------------------- ### Magic Links Routes - Ruby Source: https://context7.com/kobaltz/action_auth/llms.txt Outlines the routes for the magic link feature, including requesting a new magic link via email and signing in using the provided token. ```ruby # GET /action_auth/magics/requests/new — form to enter email # POST /action_auth/magics/requests params: { email: } # => Finds or creates user (auto-generates secure password for new users) # => Sends magic_link email # => Redirect to sign_in_path with notice # GET /action_auth/magics/sign_ins?token= # => User.find_by_token_for(:magic_token, token) # => Creates session, marks user as verified ``` -------------------------------- ### Base Action Auth Application Layout Source: https://github.com/kobaltz/action_auth/wiki/Overriding-Sign-In-page-view This is the default layout file for Action Auth. You can copy its contents and modify it to match your application's styling. Consider using your own stylesheets instead of the default Action Auth ones. ```erb Action Auth <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "action_auth/application", media: "all" %> <%= javascript_include_tag "action_auth/application", "data-turbo-track": "reload", type: "module" %> <% if ActionAuth.configuration.webauthn_enabled? %> <%= tag :meta, name: :webauthn_auth_url, content: action_auth.webauthn_credential_authentications_url %> <%= tag :meta, name: :webauthn_cred_url, content: action_auth.webauthn_credentials_url %> <%= tag :meta, name: :webauthn_redirect_url, content: action_auth.sessions_url %> <% end %>
<%= yield %>
<%= yield(:cancel_path) %>
``` -------------------------------- ### Post Model Source: https://github.com/kobaltz/action_auth/blob/main/README.md The `Post` model does not require special configuration for ActionAuth integration, as the association is handled by Rails' ActiveRecord. ```ruby # app/models/post.rb class Post < ApplicationRecord belongs_to :user end ``` -------------------------------- ### Configure SMS Authentication Source: https://context7.com/kobaltz/action_auth/llms.txt Enables SMS authentication and sets a custom class for sending verification codes. Ensure the `SmsSender` class is correctly implemented to integrate with your SMS provider. ```ruby # config/initializers/action_auth.rb ActionAuth.configure do |config| config.sms_auth_enabled = true end Rails.application.config.after_initialize do ActionAuth.configure do |config| config.sms_send_class = SmsSender end end ``` ```ruby # app/services/sms_sender.rb (example using Twilio) require "twilio-ruby" class SmsSender def self.send_code(phone_number, code) client = Twilio::REST::Client.new(ENV["TWILIO_ACCOUNT_SID"], ENV["TWILIO_AUTH_TOKEN"]) client.messages.create( from: ENV["TWILIO_PHONE_NUMBER"], to: phone_number, body: "Your verification code is #{code}" ) end end ``` -------------------------------- ### Magic Links Source: https://context7.com/kobaltz/action_auth/llms.txt Allows users to authenticate without a password by clicking a magic link sent to their email. New users are automatically registered. ```APIDOC ## Magic Links — `Magics::RequestsController` + `Magics::SignInsController` Enabled via `config.magic_link_enabled = true`. Users enter their email; a 20-minute signed token is emailed. Clicking the link authenticates the user without a password. New users are automatically registered. ### GET /action_auth/magics/requests/new Displays the form to enter the user's email for a magic link. ### POST /action_auth/magics/requests **Parameters** - **email** (string) - Required - The email address of the user. Finds or creates the user (auto-generates a secure password for new users), sends a magic link email, and redirects to the sign-in path with a notice. ### GET /action_auth/magics/sign_ins?token= Authenticates the user using the provided signed token, creates a session, and marks the user as verified. ``` -------------------------------- ### Display Active Sessions - ERB View Source: https://context7.com/kobaltz/action_auth/llms.txt This ERB template iterates over active sessions, displaying user agent, IP address, and last active time. It includes a button to sign out individual sessions. ```erb <%# app/views/action_auth/sessions/index.html.erb (override example) %>

Active Sessions

<% @sessions.each do |session| %>
<%= session.user_agent %> IP: <%= session.ip_address %> Last active: <%= time_ago_in_words(session.updated_at) %> <%= button_to "Sign Out", user_session_path(session), method: :delete, data: { confirm: "Sign out this device?" } %>
<% end %> ``` -------------------------------- ### Authenticated Route Constraint Source: https://github.com/kobaltz/action_auth/blob/main/README.md Implement a constraint to redirect users to a specific route, like a dashboard, if they are logged in. This provides a personalized experience for authenticated users. ```ruby class AuthenticatedConstraint def self.matches?(request) session_token = request.cookie_jar.signed[:session_token] ActionAuth::Session.exists?(session_token) end end ``` ```ruby constraints AuthenticatedConstraint do root to: 'dashboard#index' end root to: 'welcome#index' ``` -------------------------------- ### Session Management Routes - Ruby Source: https://context7.com/kobaltz/action_auth/llms.txt Defines the routes for listing active sessions and destroying individual sessions. ```ruby # GET /action_auth/sessions — lists sessions ordered by created_at desc # DELETE /action_auth/sessions/:id — destroys session, clears cookie, # sets Clear-Site-Data header ``` -------------------------------- ### Configure SMS Sender Class Source: https://github.com/kobaltz/action_auth/blob/main/README.md Define a class to handle sending SMS verification codes. This class must implement a `send_code` class method that accepts a phone number and a code. ```ruby require 'twilio-ruby' class SmsSender def self.send_code(phone_number, code) account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] from_number = ENV['TWILIO_PHONE_NUMBER'] client = Twilio::REST::Client.new(account_sid, auth_token) client.messages.create( from: from_number, to: phone_number, body: "Your verification code is #{code}" ) end end ``` -------------------------------- ### WebAuthn Meta Tags for Layout Source: https://context7.com/kobaltz/action_auth/llms.txt Includes necessary meta tags in your application layout for WebAuthn functionality. These tags help the engine's JavaScript locate the correct API endpoints for authentication and credential management. ```erb <%# app/views/layouts/action_auth/application.html.erb (required meta tags) %> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= stylesheet_link_tag "action_auth/application" %> <%= javascript_include_tag "action_auth/application", type: "module" %> <% if ActionAuth.configuration.webauthn_enabled? %> <%= tag :meta, name: :webauthn_auth_url, content: action_auth.webauthn_credential_authentications_url %> <%= tag :meta, name: :webauthn_cred_url, content: action_auth.webauthn_credentials_url %> <%= tag :meta, name: :webauthn_redirect_url, content: action_auth.sessions_url %> <% end %> ``` -------------------------------- ### Session Management Source: https://context7.com/kobaltz/action_auth/llms.txt Manage user sessions, including listing active sessions and terminating individual sessions. ```APIDOC ## Session Management — `SessionsController#index` and `#destroy` Lists all active sessions for the current user (device management) and allows terminating individual sessions. ### GET /action_auth/sessions Lists all active sessions for the current user, ordered by `created_at` in descending order. ### DELETE /action_auth/sessions/:id Destroys a specific session, clears the associated cookie, and sets the `Clear-Site-Data` header. ``` -------------------------------- ### Password Reset Routes - Ruby Source: https://context7.com/kobaltz/action_auth/llms.txt Outlines the routes and parameters for the two-step password reset process: requesting a reset and submitting a new password. ```ruby # Step 1 — Request reset # GET /action_auth/identity/password_reset/new # POST /action_auth/identity/password_reset params: { email: } # => Finds verified user, sends password_reset email with signed token # => Redirects to sign_in_path with notice (or alert if unverified) # Step 2 — Submit new password # GET /action_auth/identity/password_reset/edit?sid= # PATCH /action_auth/identity/password_reset?sid= params: { password:, password_confirmation: } # => Validates token via User.find_by_token_for!(:password_reset, sid) # => Updates password, invalidates other sessions, redirects to sign_in_path # => Rejects pwned passwords if pwned_enabled: true ``` -------------------------------- ### Account Deletion Button Source: https://context7.com/kobaltz/action_auth/llms.txt Provides a button to initiate account deletion. This button submits a DELETE request to the `users_path` and includes a confirmation dialog to prevent accidental deletion. ```erb <%# Add anywhere in your application views %>

Unhappy with the service? <%= button_to "Delete My Account", action_auth.users_path, method: :delete, data: { confirm: "Are you sure? This cannot be undone." }, class: "btn btn-danger" %>

``` -------------------------------- ### Magic Link Request Form Source: https://context7.com/kobaltz/action_auth/llms.txt Renders a form for requesting a magic link via email. This form submits to the `magics_requests_path`. ```erb <%# Magic link request form %> <%= form_with url: magics_requests_path do |form| %> <%= form.email_field :email, required: true, placeholder: "your@email.com" %> <%= form.submit "Send Magic Link" %> <% end %> ``` -------------------------------- ### Email Verification Source: https://context7.com/kobaltz/action_auth/llms.txt Handles the process of verifying user email addresses by sending a time-limited signed token via email. ```APIDOC ## Email Verification — `Identity::EmailVerificationsController` Sends a time-limited (2-day) signed token via email. Verifies the token on `GET` and marks the user as verified. ### GET /action_auth/identity/email_verification?sid= Verifies the provided signed token, marks the user as verified, and redirects to the sign-in path with a notice. ### POST /action_auth/identity/email_verification **Parameters** - **email** (string) - Required - The email address of the user to resend the verification email to. Finds the user by email and re-sends the verification email. ``` -------------------------------- ### View Layout Integration for User Authentication Source: https://github.com/kobaltz/action_auth/blob/main/README.md Include this ERB code in your view layout to conditionally display navigation links based on user sign-in status. ```erb <% if user_signed_in? %>
  • <%= link_to "Security", user_sessions_path %>
  • <%= button_to "Sign Out", user_session_path(current_session), method: :delete %>
  • <% else %>
  • <%= link_to "Sign In", new_user_session_path %>
  • <%= link_to "Sign Up", new_user_registration_path %>
  • <% end %> ``` -------------------------------- ### Generate Post Scaffold with User Association Source: https://github.com/kobaltz/action_auth/blob/main/README.md Use the Rails generator to create a scaffold for posts, establishing a `belongs_to` association with the user. This uses `user:belongs_to` for direct association. ```bash bin/rails g scaffold posts user:belongs_to title ``` -------------------------------- ### Password Reset Source: https://context7.com/kobaltz/action_auth/llms.txt Facilitates a two-step password reset process: requesting a reset email and submitting a new password using a time-limited signed token. ```APIDOC ## Password Reset — `Identity::PasswordResetsController` Two-step flow: request a reset email, then submit a new password using the 20-minute signed token. ### GET /action_auth/identity/password_reset/new Displays the form to request a password reset. ### POST /action_auth/identity/password_reset **Parameters** - **email** (string) - Required - The email address of the user requesting a password reset. Finds a verified user, sends a password reset email with a signed token, and redirects to the sign-in path with a notice. ### GET /action_auth/identity/password_reset/edit?sid= Displays the form to enter a new password using a valid signed token. ### PATCH /action_auth/identity/password_reset?sid= **Parameters** - **password** (string) - Required - The new password for the user. - **password_confirmation** (string) - Required - The confirmation of the new password. Validates the token, updates the user's password, invalidates other sessions, and redirects to the sign-in path. Rejects pwned passwords if enabled. ``` -------------------------------- ### Admin Route Constraint Source: https://context7.com/kobaltz/action_auth/llms.txt Defines a route constraint to check if a user is an administrator. Requires a `find_user` method to identify the current user. ```ruby # app/constraints/admin_constraint.rb class AdminConstraint def self.matches?(request) user = find_user(request) user&.admin? end def self.find_user(request) token = request.cookie_jar.signed[:session_token] session = ActionAuth::Session.find_by(id: token) session&.user&.becomes(User) end end ``` -------------------------------- ### Password Change Source: https://context7.com/kobaltz/action_auth/llms.txt Allows authenticated users to change their current password, requiring the current password as a challenge. ```APIDOC ## Password Change — `PasswordsController` Allows authenticated users to change their current password. Requires the current password as a challenge. ### GET /action_auth/password/edit Displays the form to change the current password. ### PATCH /action_auth/password **Parameters** - **password_challenge** (string) - Required - The user's current password. - **password** (string) - Required - The new password (minimum 12 characters). - **password_confirmation** (string) - Required - The confirmation of the new password. On success, all other sessions are destroyed, and the user is redirected to sign-in. ``` -------------------------------- ### Add Pwned Gem for Password Security Source: https://github.com/kobaltz/action_auth/blob/main/README.md Integrate the 'pwned' gem to leverage the Have I Been Pwned service for checking password compromises. This enhances password security by ensuring users do not use breached passwords. ```ruby bundle add pwned ``` -------------------------------- ### Send Password Reset Email Source: https://context7.com/kobaltz/action_auth/llms.txt Initiates the sending of a password reset email to the specified user. This action is designed to be called from a controller and uses `deliver_later` for background processing. ```ruby # Password reset email (expires in 20 minutes) ActionAuth::UserMailer.with(user: user).password_reset.deliver_later ``` -------------------------------- ### Email Change Routes - Ruby Source: https://context7.com/kobaltz/action_auth/llms.txt Defines the routes for editing and patching the user's email address. Changing the email triggers a new verification email and redirects to the sign-in page. ```ruby # GET /action_auth/identity/email/edit # PATCH /action_auth/identity/email params: { email:, password_challenge: } # # On email change: # => user.verified set to false # => New verification email sent via UserMailer # => Redirect to sign_in_path with notice ``` -------------------------------- ### Extend ActionAuth::User Model Source: https://context7.com/kobaltz/action_auth/llms.txt Inherit from ActionAuth::User in your host application's User model to add custom associations and logic. Ensure your ActiveSupport::CurrentAttributes class can access the user. ```ruby class User < ActionAuth::User has_many :posts, dependent: :destroy has_many :comments, dependent: :destroy end ``` ```ruby class Current < ActiveSupport::CurrentAttributes def user ActionAuth::Current.user&.becomes(User) end end ``` -------------------------------- ### Authenticated Route Constraint Source: https://context7.com/kobaltz/action_auth/llms.txt Defines a route constraint to check if a user is authenticated by verifying the existence of an ActionAuth session token. ```ruby # app/constraints/authenticated_constraint.rb class AuthenticatedConstraint def self.matches?(request) token = request.cookie_jar.signed[:session_token] ActionAuth::Session.exists?(token) end end ``` -------------------------------- ### Email Change Source: https://context7.com/kobaltz/action_auth/llms.txt Enables authenticated users to update their email address. A new verification email is automatically sent upon email change. ```APIDOC ## Email Change — `Identity::EmailsController` Allows authenticated users to update their email address. A new verification email is sent automatically when the email changes. ### GET /action_auth/identity/email/edit Displays the form to change the user's email address. ### PATCH /action_auth/identity/email **Parameters** - **email** (string) - Required - The new email address for the user. - **password_challenge** (string) - Required - The user's current password. On email change, the user's `verified` status is set to `false`, a new verification email is sent, and the user is redirected to sign-in with a notice. ``` -------------------------------- ### Admin Route Constraint Source: https://github.com/kobaltz/action_auth/blob/main/README.md Define a constraint to restrict access to specific routes, such as administrative interfaces, based on user roles. This ensures sensitive areas are only accessible to authorized personnel. ```ruby class AdminConstraint def self.matches?(request) user = current_user(request) user && user.admin? end def self.current_user(request) session_token = request.cookie_jar.signed[:session_token] session = ActionAuth::Session.find_by(id: session_token) return nil unless session.present? session.action_auth_user&.becomes(User) end end ``` ```ruby constraints AdminConstraint do mount GoodJob::Engine => 'good_job' end ``` -------------------------------- ### Password Change Form - ERB Source: https://context7.com/kobaltz/action_auth/llms.txt An ERB form for authenticated users to change their password. It requires the current password, new password, and password confirmation. ```erb <%# GET /action_auth/password/edit %> <%= form_with url: password_path, method: :patch do |form| %> <%= form.password_field :password_challenge, required: true, autocomplete: "current-password", placeholder: "Current password" %> <%= form.password_field :password, required: true, autocomplete: "new-password", placeholder: "New password (min 12 chars)" %> <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password" %> <%= form.submit "Update Password" %> <% end %> <%# PATCH /action_auth/password — on success: all other sessions destroyed, redirect to sign_in %> ``` -------------------------------- ### Password Reset Request Form - ERB Source: https://context7.com/kobaltz/action_auth/llms.txt An ERB form for requesting a password reset. It takes an email address as input and submits it to the password reset path. ```erb <%# Request form %> <%= form_with url: identity_password_reset_path do |form| %> <%= form.email_field :email, required: true, placeholder: "your@email.com" %> <%= form.submit "Send Reset Instructions" %> <% end %> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.