### Full Clearance Configuration Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md An example of how to configure various aspects of Clearance in an initializer file. ```ruby # config/initializers/clearance.rb Clearance.configure do |config| # Authentication settings config.user_model = "User" config.password_strategy = Clearance::PasswordStrategies::BCrypt # Route control config.allow_sign_up = true config.allow_password_reset = true config.routes = true # Cookie settings config.cookie_name = "remember_token" config.cookie_path = "/" config.cookie_domain = ".example.com" # or lambda for multi-tenant config.cookie_expiration = lambda { |cookies| 30.days.from_now.utc } config.httponly = true config.secure_cookie = Rails.env.production? config.signed_cookie = true config.same_site = "Lax" # Redirect URLs config.redirect_url = "/" config.url_after_destroy = "/sign_in" config.url_after_denied_access_when_signed_out = "/sign_in" # Email config.mailer_sender = "noreply@example.com" # Security config.rotate_csrf_on_sign_in = true config.sign_in_on_password_reset = false # Sign-in guards config.sign_in_guards = ["EmailConfirmationGuard"] # Controllers config.parent_controller = "ApplicationController" end ``` -------------------------------- ### Setup Project Source: https://github.com/thoughtbot/clearance/blob/main/CONTRIBUTING.md Run this command after forking the repository to set up the project locally. ```bash ./bin/setup ``` -------------------------------- ### Cookie Configuration Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Demonstrates how to configure various cookie-related options for session management. ```ruby Clearance.configure do |config| config.cookie_name = "session_token" config.cookie_domain = lambda { |request| request.host } config.cookie_expiration = lambda { |cookies| 30.days.from_now } config.secure_cookie = Rails.env.production? config.signed_cookie = true end ``` -------------------------------- ### Create User Request Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md This example shows the raw HTTP request format for creating a new user account via the /users endpoint. Ensure the 'user' parameter name matches your configuration. ```http POST /users HTTP/1.1 Content-Type: application/x-www-form-urlencoded user[email]=newuser@example.com&user[password]=mypassword ``` -------------------------------- ### Initiate Password Reset Request Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md This example demonstrates the HTTP request format for initiating a password reset by sending an email address to the /passwords endpoint. ```http POST /passwords HTTP/1.1 Content-Type: application/x-www-form-urlencoded password[email]=user@example.com ``` -------------------------------- ### Sign-In Request Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md Example of a direct HTTP POST request to the sessions endpoint for signing in a user. This format is used for non-form submissions. ```http POST /sessions HTTP/1.1 Content-Type: application/x-www-form-urlencoded session[email]=user@example.com&session[password]=mypassword ``` -------------------------------- ### Password Reset Link Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md An example of a link generated for initiating a password reset, pointing to the /passwords/new path. ```erb <%= link_to "Forgot Password?", new_password_path %> ``` -------------------------------- ### Initialize DefaultSignInGuard Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Example of initializing the `Clearance::DefaultSignInGuard`, which is the final guard in the sign-in stack. ```ruby guard = Clearance::DefaultSignInGuard.new(session) status = guard.call ``` -------------------------------- ### Custom Sign-In Guard Configuration Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Example of configuring custom sign-in guards in an initializer file. ```ruby # config/initializers/clearance.rb Clearance.configure do |config| config.sign_in_guards = ["EmailVerifiedGuard", "TwoFactorGuard"] end ``` -------------------------------- ### User Password Assignment and Verification Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/password-strategies.md Demonstrates how to create a user, assign a password, and then verify it using the `authenticated?` method. ```ruby # Usage: user = User.new(email: "user@example.com") user.password = "mypassword" user.save # Verify password if user.authenticated?("mypassword") puts "Password correct!" end ``` -------------------------------- ### Run Clearance Install Generator Source: https://github.com/thoughtbot/clearance/blob/main/README.md After installing the gem, run the generator to set up Clearance in your Rails application. This includes integrating with your User model and ApplicationController, creating an initializer, and generating a migration. ```sh rails generate clearance:install ``` -------------------------------- ### SuccessStatus Usage Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/types.md Demonstrates how to check for a successful sign-in status within a block provided by `session.sign_in`. ```ruby session.sign_in(user) do |status| if status.success? redirect_to dashboard_path end end ``` -------------------------------- ### GET /sign_up Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md Displays the user registration form if sign-up is enabled. Requires email, password, and password confirmation. ```APIDOC ## GET /sign_up ### Description Displays the user registration form if sign-up is enabled. Requires email, password, and password confirmation. ### Method GET ### Endpoint /sign_up ### Authentication Not required (but visible only if `allow_sign_up?` is true) ### Enabled Only if `Configuration#allow_sign_up?` is true ### Response #### Success Response (200 OK) - **Content-Type**: text/html - **Body**: HTML form with email, password, and password confirmation fields ### Redirect Behavior If user is already signed in, redirects to `Clearance.configuration.redirect_url`. ### Request Example ```erb <%= link_to "Sign Up", sign_up_path %> ``` ``` -------------------------------- ### Handle Authentication and Sign-In in Controller Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md An example demonstrating how to use `authenticate` to find a user and then `sign_in` to log them in, with fallback for invalid credentials. ```ruby class SessionsController < ApplicationController def create @user = authenticate(params) if @user sign_in(@user) redirect_to dashboard_path else flash[:alert] = "Invalid email or password" render :new end end end ``` -------------------------------- ### Complete RSpec View Spec Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/testing.md An RSpec example for testing view templates, demonstrating how to render views with different user states (signed-out, signed-in, admin) and check for expected elements. ```ruby # spec/views/layouts/header.html.erb_spec.rb require "rails_helper" describe "layouts/header.html.erb" do it "shows navigation for signed-out users" do render expect(rendered).to have_link("Sign In", href: sign_in_path) expect(rendered).to have_link("Sign Up", href: sign_up_path) end it "shows user menu for signed-in users" do user = build(:user, email: "alice@example.com") sign_in_as(user) render expect(rendered).to have_text("alice@example.com") expect(rendered).to have_link("Sign Out", href: sign_out_path) expect(rendered).not_to have_link("Sign In") end it "shows admin menu for admin users" do admin = build(:user, role: "admin") sign_in_as(admin) render expect(rendered).to have_link("Admin Panel", href: admin_path) end end ``` -------------------------------- ### Password Reset URL Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md An example of a URL that would be included in a password reset email, allowing a user to navigate to the password edit form with a token. ```url https://example.com/users/123/password/edit?token=abc123def456 ``` -------------------------------- ### Authentication Flow Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/index.md This outlines the typical steps involved in user authentication using Clearance, from visiting the sign-in page to successful session establishment. ```text 1. User visits GET /sign_in 2. User submits POST /sessions with email & password 3. Clearance calls User.authenticate(email, password) 4. User found → password verified 5. Session#sign_in runs guard stack 6. Guards validate (email verified, not suspended, etc.) 7. On success: Sets remember_token cookie, redirects 8. On failure: Shows error, re-renders form ``` -------------------------------- ### FailureStatus Usage Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/types.md Shows how to handle a failed sign-in status by displaying the `failure_message` and rendering an unauthorized response. ```ruby session.sign_in(user) do |status| unless status.success? flash.now[:alert] = status.failure_message render :new, status: :unauthorized end end ``` -------------------------------- ### Complete RSpec Controller Spec Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/testing.md A comprehensive RSpec example for testing controller actions, including authentication checks, post creation, and access control for editing. ```ruby # spec/controllers/posts_controller_spec.rb require "rails_helper" describe PostsController do describe "#index" do it "is accessible to anyone" do get :index expect(response).to be_successful end end describe "#create" do it "requires authentication" do post :create, params: { post: { title: "Test" } } expect(controller).to deny_access end it "creates post for signed-in user" do user = create(:user) sign_in_as(user) expect { post :create, params: { post: { title: "New Post" } } }.to change(Post, :count).by(1) expect(Post.last.user).to eq(user) expect(response).to redirect_to(post_path(Post.last)) end end describe "#edit" do let(:post) { create(:post) } it "denies access to signed-out users" do get :edit, params: { id: post.id } expect(controller).to deny_access end it "denies access to other users" do other_user = create(:user) sign_in_as(other_user) get :edit, params: { id: post.id } expect(response).to redirect_to(dashboard_path) end it "allows the post author to edit" do sign_in_as(post.user) get :edit, params: { id: post.id } expect(response).to be_successful expect(assigns(:post)).to eq(post) end end end ``` -------------------------------- ### Password Reset Flow Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/index.md This details the sequence of actions for handling password resets, from initial request to updating the password and re-establishing sessions. ```text 1. User requests reset at GET /passwords/new 2. User submits email at POST /passwords 3. If user found: Generate confirmation_token, send email 4. User clicks link in email 5. GET /users/:id/password/edit?token=... 6. User submits new password at PATCH /users/:id/password 7. User.update_password validates and saves 8. New remember_token generated (sign out all sessions) 9. User optionally signed in based on config ``` -------------------------------- ### GET /sign_in Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md Displays the sign-in form. If the user is already signed in, it redirects to the configured redirect URL. ```APIDOC ## GET /sign_in ### Description Displays the sign-in form. If the user is already signed in, it redirects to the configured redirect URL. ### Method GET ### Endpoint /sign_in ### Response #### Success Response (200 OK) - **Content-Type**: text/html - **Body**: HTML form with email and password fields ### Request Example ```erb <%= link_to "Sign In", sign_in_path %> ``` ``` -------------------------------- ### Basic Clearance Setup Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/index.md Configure Clearance by setting the mailer sender, redirect URL, and custom sign-in guards. Include the Clearance::User module in your User model and Clearance::Controller in your ApplicationController. ```ruby # config/initializers/clearance.rb Clearance.configure do |config| config.mailer_sender = "noreply@example.com" config.redirect_url = "/dashboard" config.sign_in_guards = ["EmailVerifiedGuard"] end # app/models/user.rb class User < ApplicationRecord include Clearance::User end # app/controllers/application_controller.rb class ApplicationController < ActionController::Base include Clearance::Controller end ``` -------------------------------- ### Configure Scrypt Password Strategy Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/password-strategies.md Sets the Scrypt password strategy for Clearance. Ensure the scrypt library is installed. ```ruby require_relative "../../lib/password_strategies/scrypt" Clearance.configure do |config| config.password_strategy = PasswordStrategies::Scrypt end ``` -------------------------------- ### Configure FactoryBot for User Model Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/testing.md Example of configuring FactoryBot to create user records with default attributes for testing purposes. ```ruby # spec/factories/users.rb FactoryBot.define do factory :user do email { Faker::Internet.email } password { "password123" } email_verified { true } end end ``` -------------------------------- ### Display Welcome Message Conditionally Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md An example of using `current_user` in a view to conditionally display a welcome message. ```erb <% if current_user %>
Welcome, <%= current_user.email %>
<% end %> ``` -------------------------------- ### Authorization Flow Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/index.md This describes the process of enforcing access control in controllers using Clearance's `require_login` and `deny_access` methods. ```text 1. Controller has before_action :require_login 2. Request comes in 3. Controller checks signed_in? 4. If no user: Call deny_access 5. If HTML request: Redirect to sign_in_path, store return_to 6. If JSON/XML: Return 401 Unauthorized 7. After sign-in: Redirect back to return_to ``` -------------------------------- ### HTTP 422 Unprocessable Entity Response Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/errors.md This example shows an HTTP 422 Unprocessable Entity response, used for various invalid user actions like registration, password reset, or update. The response includes the form re-rendered with error messages. ```http HTTP/1.1 422 Unprocessable Entity Content-Type: text/html ``` -------------------------------- ### Handle Sign In in SessionsController Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Example of handling user sign-in within a SessionsController, including authentication, guard execution, and redirecting or rendering based on the sign-in status. ```ruby class SessionsController < ApplicationController def create @user = User.authenticate(email, password) clearance_session.sign_in(@user) do |status| if status.success? redirect_to dashboard_path else flash.now[:alert] = status.failure_message render :new end end end end ``` -------------------------------- ### Handle Sign-In Outcome in Controller Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md An example of using the `sign_in` block to handle successful sign-ins by redirecting or displaying errors on failure. ```ruby class SessionsController < ApplicationController def create @user = authenticate(params) sign_in(@user) do |status| if status.success? redirect_to dashboard_path else flash[:alert] = status.failure_message render :new end end end end ``` -------------------------------- ### User Registration Form Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md An HTML form for user registration that submits data to the /users endpoint. It includes fields for email and password, and requires an authenticity token. ```html ``` -------------------------------- ### Clearance::SuccessStatus Instance Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Example of creating and checking the status of a `Clearance::SuccessStatus` object, which indicates a successful sign-in. ```ruby status = Clearance::SuccessStatus.new status.success? # => true ``` -------------------------------- ### Get Allowed User Actions Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md Returns an array of symbols representing allowed controller actions for users. This is typically `[:create]` if sign-up is enabled. ```ruby Clearance.configuration.user_actions # => [:create] or [] ``` -------------------------------- ### SignedIn Constraint Usage Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/types.md Demonstrates how to use the SignedIn routing constraint in Rails routes. It shows usage with and without a block to specify additional user requirements. ```ruby constraints Clearance::Constraints::SignedIn.new do resources :admin end constraints Clearance::Constraints::SignedIn.new { |user| user.admin? } do resources :settings end ``` -------------------------------- ### Implement Email Verification Guard Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Example of a custom sign-in guard that checks if the user's email is verified before allowing sign-in. It returns failure if the email is not verified. ```ruby class EmailVerifiedGuard < Clearance::SignInGuard def call if signed_in? && current_user.email_verified? next_guard else failure("You must verify your email before signing in") end end end ``` -------------------------------- ### Implement Custom Password Strategy Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/password-strategies.md Defines a custom password strategy module that must include `authenticated?` and `password=` methods. This example uses the SCrypt algorithm. ```ruby # lib/password_strategies/scrypt.rb module PasswordStrategies module Scrypt def authenticated?(password) if encrypted_password.present? ::SCrypt::Password.new(encrypted_password) == password end end def password=(new_password) @password = new_password if new_password.present? self.encrypted_password = ::SCrypt::Password.create(new_password) end end end end ``` -------------------------------- ### Get Configured User Model Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md Retrieves the user model class that Clearance is configured to use. The string name is automatically constantized. ```ruby Clearance.configuration.user_model # => User class ``` -------------------------------- ### Implementing a Custom Email Verification Guard Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md Create a custom sign-in guard by inheriting from `Clearance::SignInGuard` and implementing the `call` method. This example checks if the user's email is verified before allowing sign-in. ```ruby # app/guards/email_verified_guard.rb class EmailVerifiedGuard < Clearance::SignInGuard def call if signed_in? && current_user.email_verified? next_guard else failure("You must verify your email before signing in.") end end end ``` -------------------------------- ### Test Sign-In Guards with RSpec Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/testing.md An RSpec example for testing custom sign-in guards, such as an EmailVerifiedGuard, to ensure proper access control based on user attributes. ```ruby # spec/guards/email_verified_guard_spec.rb require "rails_helper" describe EmailVerifiedGuard do let(:session) { Clearance::Session.new(env) } let(:stack) { spy(:next_guard) } subject { EmailVerifiedGuard.new(session, stack) } it "calls next guard if email is verified" do user = create(:user, email_verified: true) session.sign_in(user) subject.call expect(stack).to have_received(:call) end it "fails if email is not verified" do user = create(:user, email_verified: false) session.sign_in(user) status = subject.call expect(status).to be_a(Clearance::FailureStatus) expect(status.failure_message).to include("verify") end end ``` -------------------------------- ### Handle User Sign-Out in Controller Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md An example of calling `sign_out` in a controller action to end the user's session and redirect them to the sign-in page. ```ruby class SessionsController < ApplicationController def destroy sign_out redirect_to sign_in_path end end ``` -------------------------------- ### User Model Password Strategy Testing Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/password-strategies.md Provides example RSpec tests for a User model using Clearance's password strategies. It covers password encryption, authentication with correct passwords, and rejection of incorrect passwords. ```ruby # spec/models/user_spec.rb describe User do describe "password strategy" do it "encrypts password on assignment" do user = User.new(password: "secret") expect(user.encrypted_password).to be_present expect(user.encrypted_password).not_to eq("secret") end it "authenticates with correct password" do user = User.create( email: "user@example.com", password: "correct" ) expect(user.authenticated?("correct")).to be true end it "rejects incorrect password" do user = User.create( email: "user@example.com", password: "correct" ) expect(user.authenticated?("wrong")).to be_falsy end end end ``` -------------------------------- ### HTTP 401 Unauthorized Response Example Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/errors.md This is an example of an HTTP 401 Unauthorized response, typically returned after a failed sign-in attempt. The response includes the sign-in form re-rendered with an error. ```http HTTP/1.1 401 Unauthorized Content-Type: text/html ``` -------------------------------- ### Custom Email Verification Guard Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md An example of a custom sign-in guard that ensures the user's email has been verified before allowing sign-in. This guard should be added to the Clearance configuration. ```ruby # app/guards/email_verified_guard.rb class EmailVerifiedGuard < Clearance::SignInGuard def call if signed_in? && current_user.email_verified? next_guard else failure("You must verify your email before signing in") end end end # config/initializers/clearance.rb Clearance.configure do |config| config.sign_in_guards = ["EmailVerifiedGuard"] end ``` -------------------------------- ### GET /passwords/new Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md Displays the password reset request form. This endpoint is enabled only if `Configuration#allow_password_reset?` is true. It presents a form for users to enter their email address to initiate the password reset process. ```APIDOC ## GET /passwords/new ### Description Displays the password reset request form. This endpoint is enabled only if `Configuration#allow_password_reset?` is true. It presents a form for users to enter their email address to initiate the password reset process. ### Method GET ### Endpoint /passwords/new ### Response #### Success Response (200 OK) - **Content-Type**: text/html - **Body**: HTML form with email field ``` -------------------------------- ### Sign-In Guard Execution Flow Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Illustrates the step-by-step execution flow of sign-in guards, showing how each guard's result determines whether to proceed to the next guard or return a failure. ```text sign_in(user) ↓ create guard stack: EmailVerifiedGuard → TwoFactorGuard → DefaultSignInGuard ↓ EmailVerifiedGuard#call ├─ verified? → next_guard └─ not verified? → failure("verify email") (if not verified, stops here with FailureStatus) If verified: TwoFactorGuard#call ├─ 2fa enabled? → failure("2fa required") └─ 2fa disabled? → next_guard (if 2fa enabled, stops here with FailureStatus) If no 2fa: DefaultSignInGuard#call ├─ signed in? → success └─ not signed in? → failure("bad credentials") ``` -------------------------------- ### Get User ID Parameter Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md Retrieves the foreign key parameter name for the user model. ```ruby Clearance.configuration.user_id_parameter # => :user_id ``` -------------------------------- ### Controller Usage for Sign-In with Guards Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Demonstrates how to use the `sign_in` method in a controller, yielding to a block that handles success or failure based on guard execution. ```ruby class SessionsController < ApplicationController def create @user = authenticate(params) sign_in(@user) do |status| if status.success? # User passed all guards redirect_to dashboard_path else # A guard failed flash.now[:alert] = status.failure_message render :new, status: :unauthorized end end end end ``` -------------------------------- ### Build and Publish Gem Source: https://github.com/thoughtbot/clearance/blob/main/RELEASING.md Commands to build the gem locally and push it to a gem repository. ```bash gem build clearance.gemspec gem push clearance-*.gem ``` -------------------------------- ### Sign in user in tests with Clearance Source: https://github.com/thoughtbot/clearance/wiki/Usage Use the `sign_in_as` helper within your test suite to simulate a logged-in user. Ensure you have a factory defined for creating users. ```ruby context "when signed in on GET to new" do setup do @user = Factory(:email_confirmed_user) sign_in_as @user get :new end should_respond_with :success end ``` -------------------------------- ### Initialize Custom Sign-In Guard Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Demonstrates how to initialize a custom sign-in guard by inheriting from Clearance::SignInGuard. The constructor accepts the current session and the next guard in the chain. ```ruby class MyGuard < Clearance::SignInGuard def initialize(session, stack = []) super end end ``` -------------------------------- ### Run Tests Source: https://github.com/thoughtbot/clearance/blob/main/CONTRIBUTING.md Execute all tests using the Appraisal tool to ensure a clean slate before making changes. ```bash bundle exec appraisal rake ``` -------------------------------- ### Configure Allowed Backdoor Environments Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/errors.md Shows how to configure the allowed environments for using the BackDoor middleware in Clearance. This helps prevent accidental use in production. ```ruby # Allowed environments (configurable) Clearance.configure do |config| config.allowed_backdoor_environments = ["test", "ci", "development"] end ``` -------------------------------- ### Get Current User Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md Returns the currently signed-in user or nil if no user is authenticated. Accessible in controllers and views. ```ruby current_user # => User instance or nil ``` -------------------------------- ### Get User Parameter Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md Retrieves the parameter name used for user routes, derived from the user model name. ```ruby Clearance.configuration.user_parameter # => :user ``` -------------------------------- ### Get Current Clearance Configuration Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md Retrieves the current configuration object for Clearance. This object holds all active settings. ```ruby Clearance.configuration # => returns current Configuration instance ``` -------------------------------- ### POST /users Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md Creates a new user account. This endpoint is enabled only if `Configuration#allow_sign_up?` is true. It handles user registration, sets a remember token, and automatically signs the user in upon successful creation. ```APIDOC ## POST /users ### Description Creates a new user account. This endpoint is enabled only if `Configuration#allow_sign_up?` is true. It handles user registration, sets a remember token, and automatically signs the user in upon successful creation. ### Method POST ### Endpoint /users ### Parameters #### Request Body - **user[email]** (String) - Yes - Email address (must be unique) - **user[password]** (String) - Yes - Password *Note: The parameter name `user` can be customized via `Configuration#user_parameter`.* ### Request Example ``` POST /users HTTP/1.1 Content-Type: application/x-www-form-urlencoded user[email]=newuser@example.com&user[password]=mypassword ``` ### Response #### Success Response (302 Found) - **Location**: Value of `Configuration#redirect_url` (default: `/`) - **Headers**: Sets `remember_token` cookie (user is automatically signed in) #### Error Response (422 Unprocessable Entity) - **Content-Type**: text/html - **Body**: Re-renders registration form with validation errors ### Validation - Email: Required, unique, valid email format (strict mode), normalized (lowercased, spaces removed) - Password: Required ### Side Effects - Creates new user record - Generates `remember_token` - Signs in the user automatically ``` -------------------------------- ### Email Optional Validation Hook Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/user.md Override to return true if email should be optional, for example, for username-based authentication. Defaults to false. ```ruby def email_optional? false # Default: email is required end ``` -------------------------------- ### Use Current User in Controller Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Example of how to access the current user within an ApplicationController using the clearance_session helper method. ```ruby class ApplicationController < ActionController::Base def current_user clearance_session.current_user end end ``` -------------------------------- ### Sign In User with Callback Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Signs in a user, runs configured guards, and yields a status object to a block. Handles success or failure messages. ```ruby session.sign_in(user) do |status| if status.success? # Handle successful sign-in else # status.failure_message contains reason for failure end end ``` -------------------------------- ### Clearance::FailureStatus Success Check Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/sign-in-guard.md Example of checking the `success?` method on a `Clearance::FailureStatus` object, which always returns false. ```ruby status = Clearance::FailureStatus.new("Not allowed") status.success? # => false ``` -------------------------------- ### Get Clearance Session Object Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md Returns the `Clearance::Session` instance from the Rack environment. This is a protected method primarily for implementers. ```ruby clearance_session # => Clearance::Session instance ``` -------------------------------- ### Test Controller Actions with Clearance Helpers Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/testing.md Demonstrates how to use Clearance's test helpers within Test::Unit functional tests to simulate user sign-in and test protected actions. ```ruby class PostsControllerTest < ActionController::TestCase def test_create_requires_login assert_raises(ActionController::RoutingError) do post :create, params: { post: { title: "Test" } } end end def test_signed_in_user_can_create user = create(:user) sign_in_as(user) post :create, params: { post: { title: "Test" } } assert_redirected_to(post_path(assigns(:post))) end end ``` -------------------------------- ### Get Parent Controller Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/configuration.md Retrieves the base controller class from which Clearance controllers inherit. This allows customization of the controller hierarchy. ```ruby Clearance.configuration.parent_controller # => ApplicationController class ``` -------------------------------- ### Password Optional Validation Hook Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/user.md Override to return true if password should be optional, for example, for social login integration. Defaults to false. ```ruby def password_optional? false # Default: password is required end ``` -------------------------------- ### Handle Authentication Failure During Sign-In Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/errors.md Shows how to handle a failed sign-in attempt due to incorrect credentials by checking the status object and displaying an alert message. ```ruby session.sign_in(user) do |status| unless status.success? # status.failure_message => "Bad email or password." flash[:alert] = status.failure_message end end ``` -------------------------------- ### Sign-In Guard Stack Execution Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Illustrates the default sign-in guard and how custom guards are configured and injected into the stack. ```ruby default_guard = DefaultSignInGuard.new(self) guards = Clearance.configuration.sign_in_guards guards.inject(default_guard) do |stack, guard_class| guard_class.to_s.constantize.new(self, stack) end ``` -------------------------------- ### Handle Sign Out in SessionsController Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Example of handling user sign-out within a SessionsController, which involves calling `clearance_session.sign_out` and redirecting to the sign-in page. ```ruby class SessionsController < ApplicationController def destroy clearance_session.sign_out redirect_to sign_in_path end end ``` -------------------------------- ### Clearance::Session#initialize Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Creates a new session instance for the current request environment. This method is called internally by the Clearance::RackSession middleware. ```APIDOC ## Clearance::Session#initialize(env) ### Description Creates a new session instance for the current request environment. ### Parameters - **env** (Hash) - The Rack environment hash ### Returns Clearance::Session instance ### Source `lib/clearance/session.rb:8-12` ``` -------------------------------- ### authenticate(params) Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/authentication.md Authenticates a user with provided email and password parameters. Expects `params` to have the structure: `{ session: { email: "user@example.com", password: "password" } }`. Returns the user if authentication succeeds, nil otherwise. ```APIDOC ## authenticate(params) ### Description Authenticates a user with provided email and password parameters. Expects `params` to have the structure: ```ruby { session: { email: "user@example.com", password: "password" } } ``` Returns the user if authentication succeeds, nil otherwise. ### Parameters #### Required - **params** (ActionController::Parameters) - Must contain `params[:session][:email]` and `params[:session][:password]` ### Returns User instance or nil ### Example ```ruby class SessionsController < ApplicationController def create @user = authenticate(params) if @user sign_in(@user) redirect_to dashboard_path else flash[:alert] = "Invalid email or password" render :new end end end ``` ``` -------------------------------- ### Custom User Model Validation Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/errors.md Example of adding custom validations to the User model, including presence and uniqueness for username, and overriding email optionality. ```ruby class User < ApplicationRecord include Clearance::User validates :username, presence: true, uniqueness: true def email_optional? username.present? # Use username instead end end ``` -------------------------------- ### Initialize Clearance::Session Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Creates a new session instance for the current request environment. Requires the Rack environment hash. ```ruby session = Clearance::Session.new(env) ``` -------------------------------- ### Create a New User Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/user.md Creates a new user with an email and password. The user will automatically have a remember token generated upon saving. ```ruby # Create a new user user = User.new(email: "user@example.com", password: "secure_password") if user.save # User created, automatically has remember_token end ``` -------------------------------- ### Get Remember Token Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Retrieves the remember token value from the cookie, handling signed and unsigned cookie logic based on configuration. This is a private method. ```ruby session.remember_token ``` -------------------------------- ### Configure BCrypt Migration From SHA1 Strategy Source: https://github.com/thoughtbot/clearance/wiki/Upgrading-Clearance Use this configuration to transition users from SHA1 to BCrypt encryption strategy in Clearance. ```ruby Clearance.configure do |config| config.password_strategy = Clearance::PasswordStrategies::BCryptMigrationFromSHA1 end ``` -------------------------------- ### Get Current User from Session Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/session.md Retrieves the current user by looking up the remember token in the cookie. The result is cached to prevent redundant database queries. ```ruby session = request.env[:clearance] user = session.current_user # => User or nil ``` -------------------------------- ### Set User Password Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/api-reference/user.md Sets the user's password, which gets encrypted using the configured password strategy (BCrypt by default). The plain password is not stored. ```ruby user = User.new user.password = "my_password" # Encrypts and sets encrypted_password via the password strategy ``` ```ruby user = User.new(email: "user@example.com") user.password = "newpassword" user.save ``` -------------------------------- ### POST /sessions Source: https://github.com/thoughtbot/clearance/blob/main/_autodocs/endpoints.md Creates a new session by signing in the user with provided email and password. Handles success with redirects and failure with unauthorized responses. ```APIDOC ## POST /sessions ### Description Creates a new session by signing in the user with provided email and password. Handles success with redirects and failure with unauthorized responses. ### Method POST ### Endpoint /sessions ### Parameters #### Request Body - **session[email]** (String) - Required - User's email address - **session[password]** (String) - Required - User's password (plaintext) ### Request Example ```ruby POST /sessions HTTP/1.1 Content-Type: application/x-www-form-urlencoded session[email]=user@example.com&session[password]=mypassword ``` ### Response #### Success Response (302 Found) - **Location**: Value of `Configuration#redirect_url` (default: `/`) - **Headers**: Sets `remember_token` cookie - **Cookie**: `remember_token=