Clearance Documentation

repository·main·Indexed 25 days ago

https://github.com/thoughtbot/clearance

A lightweight, opinionated Rails engine for email and password-based authentication. Clearance provides tools for managing user sessions, including the `require_login` filter, `current_user` and `signed_in?` helpers, and routing constraints. It features customizable sign-in guards, multi-domain cookie support, and the `Clearance::BackDoor` middleware for accelerating integration tests.

Tokens
5.4K
Snippets
20
Records
38
Agent score
85%

What's inside Clearance

  1. Override Clearance views and layouts

    main

    To customize the look and feel of authentication pages:

    1. Views: Copy the default views to your application using rails generate clearance:views, then modify them in your app/views directory.
    2. Layouts: Specify custom layouts for Clearance controllers in config/application.rb using config.to_prepare.
    # In config/application.rb
    config.to_prepare do
      Clearance::PasswordsController.layout "my_passwords_layout"
      Clearance::SessionsController.layout "my_sessions_layout"
      Clearance::UsersController.layout "my_admin_layout"
    end
  2. Install Clearance in Rails

    main
    Clearance is a Rails engine for email and password authentication. To install it, add the gem to your Gemfile and run the generator to set up the User model, ApplicationController integration, initializers, and migrations.
  3. Speed up feature specs with Clearance::BackDoor middleware

    main

    Clearance provides Clearance::BackDoor middleware to speed up feature specs by signing in users directly, bypassing the sign-in form.

    To enable it, add it to your test environment configuration. If you have overridden User#to_param, you can provide a block to the middleware to define how to find the user.

    # config/environments/test.rb
    MyRailsApp::Application.configure do
      # ...
      config.middleware.use Clearance::BackDoor
      # ...
    end

    Usage in tests:

    visit root_path(as: user)

    With custom to_param logic:

    # config/environments/test.rb
    MyRailsApp::Application.configure do
      # ...
      config.middleware.use Clearance::BackDoor do |username|
        Clearance.configuration.user_model.find_by(username: username)
      end
      # ...
    end
  4. Implement custom Sign In Guards

    main

    Use SignInGuards to add additional checks during the sign-in process (e.g., checking if an email is confirmed or if a user is suspended).

    1. Create a class that inherits from Clearance::SignInGuard.
    2. Implement the call method. Use next_guard to proceed to the next guard in the stack, or failure("message") to stop the process.
    3. Register the guard in the config.sign_in_guards array in your initializer.
    # 1. Define the guard
    # app/guards/email_confirmation_guard.rb
    class EmailConfirmationGuard < Clearance::SignInGuard
      def call
        if unconfirmed?
          failure("You must confirm your email address.")
        else
          next_guard
        end
      end
    
      def unconfirmed?
        signed_in? && !current_user.confirmed_at
      end
    end
    
    # 2. Register it
    # config/initializers/clearance.rb
    Clearance.configure do |config|
      config.sign_in_guards = ["EmailConfirmationGuard"]
    end
  5. Override Clearance routes and controllers

    main

    It is recommended to take full control over routing and URL design rather than using Clearance's defaults.

    1. Disable default routes: Set config.routes = false in your initializer.
    2. Generate default routes: Run rails generate clearance:routes to dump the default routes into your app for modification.
    3. Override controllers: Subclass the Clearance controllers (e.g., PasswordsController, SessionsController, UsersController) and update your routes to point to your new subclasses.
    # In your initializer
    Clearance.configure do |config|
      config.routes = false
    end
    
    # Subclassing controllers
    class PasswordsController < Clearance::PasswordsController
    class SessionsController < Clearance::SessionsController
    class UsersController < Clearance::UsersController
  6. Configure Clearance test helpers for RSpec or Test::Unit

    main

    To use Clearance controller test helpers (like sign_in, sign_in_as, and sign_out) or view spec helpers, you must require the appropriate test helper file in your test suite.

    Note for Rails 5+: Since default controller tests are now integration tests, you should use the Clearance::BackDoor middleware instead of these helpers for functional testing.

  7. Configure Clearance settings

    main

    You can customize authentication behavior in config/initializers/clearance.rb using the Clearance.configure block. Key configuration options include:

    • allow_sign_up: Boolean to enable/disable sign-ups.
    • allow_password_reset: Boolean to enable/disable password resets.
    • cookie_domain: String or callable for domain scoping.
    • cookie_expiration: A lambda returning the expiration time.
    • cookie_name: The name of the authentication cookie.
    • redirect_url: The default URL to redirect to after successful actions.
    • mailer_sender: The 'from' address for password reset emails.
    • password_strategy: The strategy used for password hashing (e.g., Clearance::PasswordStrategies::BCrypt).
    • routes: Boolean to enable/disable Clearance's default routes.
    • signed_cookie: Boolean or :migrate to enable signed cookies.
    • user_model: The name of your user model (default: "User").
    • parent_controller: The controller to include Clearance in (default: "ApplicationController").
    Clearance.configure do |config|
      config.allow_sign_up = true
      config.allow_password_reset = true
      config.cookie_domain = ".example.com"
      config.cookie_expiration = lambda { |cookies| 1.year.from_now.utc }
      config.cookie_name = "remember_token"
      config.cookie_path = "/"
      config.routes = true
      config.httponly = true
      config.mailer_sender = "reply@example.com"
      config.password_strategy = Clearance::PasswordStrategies::BCrypt
      config.redirect_url = "/"
      config.url_after_destroy = nil
      config.url_after_denied_access_when_signed_out = nil
      config.rotate_csrf_on_sign_in = true
      config.same_site = nil
      config.secure_cookie = Rails.configuration.force_ssl
      config.signed_cookie = false
      config.sign_in_guards = []
      config.user_model = "User"
      config.parent_controller = "ApplicationController"
      config.sign_in_on_password_reset = false
    end
  8. Enable Clearance::BackDoor for integration tests

    main

    The Clearance::BackDoor middleware allows you to sign in users during integration tests by passing an as=USER_ID query parameter in your URLs. This eliminates the need to manually visit and submit sign-in forms in your test suite.

    To use it, add the middleware to your application configuration, typically in config/environments/test.rb.

    # config/environments/test.rb
    MyRailsApp::Application.configure do
      # ...
      config.middleware.use Clearance::BackDoor
      # ...
    end
  9. Integrate Clearance::User into your User model

    main

    To use Clearance for authentication, include the Clearance::User module in your user model (which defaults to User, but can be changed via Configuration#user_model=). This adds authentication methods, password management, and validations to your class.

    By default, it uses PasswordStrategies::BCrypt for password handling, which can be customized via Configuration#password_strategy=.

    class User
      include Clearance::User
    
      # ...
    end
  10. Install Clearance using the Rails generator

    main

    Clearance provides a Rails generator to automate the installation process. Running the generator performs the following actions:

    1. Creates an initializer: Generates config/initializers/clearance.rb.
    2. Updates ApplicationController: Injects include Clearance::Controller into app/controllers/application_controller.rb.
    3. Sets up the User model:
      • If app/models/user.rb already exists, it injects include Clearance::User into the class.
      • If it does not exist, it generates a new app/models/user.rb template.
    4. Generates migrations:
      • If a users table does not exist, it creates a create_users migration.
      • If a users table exists, it generates a migration to add necessary columns (email, encrypted_password, confirmation_token, remember_token) and indexes if they are missing.