• Stars
    star
    3,629
  • Rank 11,651 (Top 0.3 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 15 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Rails authentication with email & password.

Clearance

Build Status Code Climate Documentation Quality Reviewed by Hound

Rails authentication with email & password.

Clearance is intended to be small, simple, and well-tested. It has opinionated defaults but is intended to be easy to override.

Please use GitHub Issues to report bugs. If you have a question about the library, please use the clearance tag on Stack Overflow. This tag is monitored by contributors.

Getting Started

Clearance is a Rails engine tested against Rails >= 6.1 and Ruby >= 3.0.0.

You can add it to your Gemfile with:

gem "clearance"

Run the bundle command to install it.

After you install Clearance, you need to run the generator:

rails generate clearance:install

The Clearance install generator:

  • Inserts Clearance::User into your User model
  • Inserts Clearance::Controller into your ApplicationController
  • Creates an initializer file to allow further configuration.
  • Creates a migration file that either create a users table or adds any necessary columns to the existing table.

Configure

Override any of these defaults in config/initializers/clearance.rb:

Clearance.configure do |config|
  config.allow_sign_up = 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 = "[email protected]"
  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 = false
  config.signed_cookie = false
  config.sign_in_guards = []
  config.user_model = "User"
  config.parent_controller = "ApplicationController"
  config.sign_in_on_password_reset = false
end

Use

Access Control

Use the require_login filter to control access to controller actions.

class ArticlesController < ApplicationController
  before_action :require_login

  def index
    current_user.articles
  end
end

Clearance also provides routing constraints that can be used to control access at the routing layer:

Blog::Application.routes.draw do
  constraints Clearance::Constraints::SignedIn.new { |user| user.admin? } do
    root to: "admin/dashboards#show", as: :admin_root
  end

  constraints Clearance::Constraints::SignedIn.new do
    root to: "dashboards#show", as: :signed_in_root
  end

  constraints Clearance::Constraints::SignedOut.new do
    root to: "marketing#index"
  end
end

Helper Methods

Use current_user, signed_in?, and signed_out? in controllers, views, and helpers. For example:

<% if signed_in? %>
  <%= current_user.email %>
  <%= button_to "Sign out", sign_out_path, method: :delete %>
<% else %>
  <%= link_to "Sign in", sign_in_path %>
<% end %>

Password Resets

When a user resets their password, Clearance delivers them an email. You should change the mailer_sender default, used in the email's "from" header:

Clearance.configure do |config|
  config.mailer_sender = "[email protected]"
end

Multiple Domain Support

You can support multiple domains, or other special domain configurations by optionally setting cookie_domain as a callable object. The first argument passed to the method is an ActionDispatch::Request object.

Clearance.configure do |config|
  config.cookie_domain = lambda { |request| request.host }
end

Integrating with Rack Applications

Clearance adds its session to the Rack environment hash so middleware and other Rack applications can interact with it:

class Bubblegum::Middleware
  def initialize(app)
    @app = app
  end

  def call(env)
    if env[:clearance].signed_in?
      env[:clearance].current_user.bubble_gum
    end

    @app.call(env)
  end
end

Overriding Clearance

Routes

See config/routes.rb for the default set of routes.

As of Clearance 1.5 it is recommended that you disable Clearance routes and take full control over routing and URL design. This ensures that your app's URL design won't be affected if the gem's routes and URL design are changed.

To disable the routes, change the routes configuration option to false:

Clearance.configure do |config|
  config.routes = false
end

You can optionally run rails generate clearance:routes to dump a copy of the default routes into your application for modification.

Controllers

See app/controllers/clearance for the default behavior. Many protected methods were extracted in these controllers in an attempt to make overrides and hooks simpler.

To override a Clearance controller, subclass it and update the routes to point to your new controller (see the "Routes" section).

class PasswordsController < Clearance::PasswordsController
class SessionsController < Clearance::SessionsController
class UsersController < Clearance::UsersController

Redirects

The post-action redirects in Clearance are simple methods which can be overridden one by one, or configured globally.

These "success" methods are called for signed in users, and redirect to Clearance.configuration.redirect_url (which is / by default):

  • passwords#url_after_update
  • sessions#url_after_create
  • sessions#url_for_signed_in_users
  • users#url_after_create
  • application#url_after_denied_access_when_signed_in

To override them all at once, change the global configuration of redirect_url. To change individual URLs, override the appropriate method in your subclassed controller.

These "failure" methods are called for signed out sessions:

  • application#url_after_denied_access_when_signed_out
  • sessions#url_after_destroy

You can override the appropriate method in your subclassed controller or you can set a configuration value for either of these URLs:

  • Clearance.configuration.url_after_denied_access_when_signed_out
  • Clearance.configuration.url_after_destroy

Both configurations default to nil and if not set will default to sign_in_url in sessions_controller.rb and authorization.rb for backwards compatibility.

Views

See app/views for the default behavior.

To override a view, create your own copy of it:

app/views/clearance_mailer/change_password.html.erb
app/views/passwords/create.html.erb
app/views/passwords/edit.html.erb
app/views/passwords/new.html.erb
app/views/sessions/_form.html.erb
app/views/sessions/new.html.erb
app/views/users/_form.html.erb
app/views/users/new.html.erb

You can use the Clearance views generator to copy the default views to your application for modification.

rails generate clearance:views

Layouts

By default, Clearance uses your application's default layout. If you would like to change the layout that Clearance uses when rendering its views, simply specify the layout in the 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

Translations

All flash messages and email subject lines are stored in i18n translations. Override them like any other translation.

See config/locales/clearance.en.yml for the default behavior.

You can also install clearance-i18n for access to additional, user-contributed translations.

User Model

See lib/clearance/user.rb for the default behavior. You can override those methods as needed.

Note that there are some model-level validations (see above link for detail) which the Clearance::User module will add to the configured model class and which may conflict with or duplicate already present validations on the email and password attributes. Over-riding the email_optional? or skip_password_validation? methods to return true will disable those validations from being added.

Signed Cookies

By default, Clearance uses unsigned cookies. If you would like to use signed cookies you can do so by overriding the default in an initializer like so:

Clearance.configure do |config|
  # ... other overrides
  config.signed_cookie = true
end

If you are currently not using signed cookies but would like to migrate your users over to them without breaking current sessions, you can do so by passing in :migrate rather than true as so:

Clearance.configure do |config|
  # ... other overrides
  config.signed_cookie = :migrate
end

You can read more about signed cookies in Clearance and why they are a good idea in the pull request that added them.

Extending Sign In

By default, Clearance will sign in any user with valid credentials. If you need to support additional checks during the sign in process then you can use the SignInGuard stack. For example, using the SignInGuard stack, you could prevent suspended users from signing in, or require that users confirm their email address before accessing the site.

SignInGuards offer fine-grained control over the process of signing in a user. Each guard is run in order and hands the session off to the next guard in the stack.

A SignInGuard is an object that responds to call. It is initialized with a session and the current stack.

On success, a guard should call the next guard or return SuccessStatus.new if you don't want any subsequent guards to run.

On failure, a guard should call FailureStatus.new(failure_message). It can provide a message explaining the failure.

For convenience, a SignInGuard class has been provided and can be inherited from. The convenience class provides a few methods to help make writing guards simple: success, failure, next_guard, signed_in?, and current_user.

Here's an example custom guard to handle email confirmation:

Clearance.configure do |config|
  config.sign_in_guards = ["EmailConfirmationGuard"]
end
# 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

Testing

Fast Feature Specs

Clearance includes middleware that avoids wasting time spent visiting, loading, and submitting the sign in form. It instead signs in the designated user directly. The speed increase can be substantial.

Enable the Middleware in Test:

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

Usage:

visit root_path(as: user)

Additionally, if User#to_param is overridden, you can pass a block in order to override the default behavior:

# 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

Ready Made Feature Specs

If you're using RSpec, you can generate feature specs to help prevent regressions in Clearance's integration with your Rails app over time. These feature specs, will also require factory_bot_rails.

To Generate the clearance specs, run:

rails generate clearance:specs

Controller Test Helpers

To test controller actions that are protected by before_action :require_login, require Clearance's test helpers in your test suite.

For rspec, add the following line to your spec/rails_helper.rb or spec/spec_helper if rails_helper does not exist:

require "clearance/rspec"

For test-unit, add this line to your test/test_helper.rb:

require "clearance/test_unit"

Note for Rails 5: the default generated controller tests are now integration tests. You will need to use the backdoor middleware instead.

This will make Clearance::Controller methods work in your controllers during functional tests and provide access to helper methods like:

sign_in
sign_in_as(user)
sign_out

View and Helper Spec Helpers

Does the view or helper you're testing reference signed_in?, signed_out? or current_user? If you require 'clearance/rspec', you will have the following helpers available in your view specs:

sign_in
sign_in_as(user)

These will make the clearance view helpers work as expected by signing in either a new instance of your user model (sign_in) or the object you pass to sign_in_as. If you do not call one of these sign in helpers or otherwise set current_user in your view specs, your view will behave as if there is no current user: signed_in? will be false and signed_out? will be true.

Contributing

Please see CONTRIBUTING.md. Thank you, contributors!

Security

For security issues it's better to contact [email protected] (See https://thoughtbot.com/security)

License

Clearance is copyright © 2009 thoughtbot. It is free software, and may be redistributed under the terms specified in the LICENSE file.

More Repositories

1

guides

A guide for programming in style.
Ruby
9,327
star
2

bourbon

A Lightweight Sass Tool Set
Ruby
9,100
star
3

paperclip

Easy file attachment management for ActiveRecord
Ruby
9,055
star
4

laptop

A shell script to set up a macOS laptop for web and mobile development.
Shell
8,416
star
5

dotfiles

A set of vim, zsh, git, and tmux configuration files.
Shell
7,864
star
6

factory_bot

A library for setting up Ruby objects as test data.
Ruby
7,826
star
7

administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
JavaScript
5,797
star
8

neat

A fluid and flexible grid Sass framework
Ruby
4,444
star
9

suspenders

A Rails template with our standard defaults, ready to deploy to Heroku.
Ruby
3,922
star
10

til

Today I Learned
3,903
star
11

Argo

Functional JSON parsing library for Swift
Swift
3,495
star
12

shoulda-matchers

Simple one-liner tests for common Rails functionality
Ruby
3,469
star
13

high_voltage

Easily include static pages in your Rails app.
Ruby
3,141
star
14

rcm

rc file (dotfile) management
Perl
2,990
star
15

factory_bot_rails

Factory Bot ♥ Rails
Ruby
2,972
star
16

shoulda

Makes tests easy on the fingers and the eyes
Ruby
2,184
star
17

expandable-recycler-view

Custom Android RecyclerViewAdapters that collapse and expand
Java
2,073
star
18

capybara-webkit

A Capybara driver for headless WebKit to test JavaScript web apps
Ruby
1,976
star
19

gitsh

An interactive shell for git
Ruby
1,957
star
20

Tropos

Weather and Forecasts for Humans
Swift
1,518
star
21

refills

[no longer maintained]
CSS
1,513
star
22

design-sprint

Product Design Sprint Material
1,415
star
23

bitters

Add a dash of pre-defined style to your Bourbon.
HTML
1,398
star
24

griddler

Simplify receiving email in Rails
Ruby
1,375
star
25

trail-map

Trails to help designers and developers learn various topics.
1,219
star
26

appraisal

A Ruby library for testing your library against different versions of dependencies.
Ruby
1,194
star
27

hotwire-example-template

A collection of branches that transmit HTML over the wire.
Ruby
989
star
28

parity

Shell commands for development, staging, and production parity for Heroku apps
Ruby
882
star
29

Runes

Infix operators for monadic functions in Swift
Swift
829
star
30

cocaine

A small library for doing (command) lines.
Ruby
788
star
31

fishery

A library for setting up JavaScript objects as test data
TypeScript
759
star
32

flutie

View helpers for Rails applications
Ruby
730
star
33

TBAnnotationClustering

Example App: How To Efficiently Display Large Amounts of Data on iOS Maps
Objective-C
728
star
34

ember-cli-rails

Unify your EmberCLI and Rails Workflows
Ruby
714
star
35

vim-rspec

Run Rspec specs from Vim
Vim Script
650
star
36

climate_control

Modify your ENV
Ruby
512
star
37

constable

Better company announcements
Elixir
511
star
38

carnival

An unobtrusive, developer-friendly way to add comments
Haskell
501
star
39

ruby-science

The reference for writing fantastic Rails applications
Ruby
494
star
40

Curry

Swift implementations for function currying
Swift
493
star
41

pacecar

Generated scopes for ActiveRecord classes
Ruby
437
star
42

hoptoad_notifier

Reports exceptions to Hoptoad
Ruby
408
star
43

fake_stripe

A Stripe fake so that you can avoid hitting Stripe servers in tests.
Ruby
393
star
44

json_matchers

Validate your JSON APIs
Ruby
381
star
45

Swish

Nothing but Net(working)
Swift
364
star
46

paul_revere

A library for "one off" announcements in Rails apps.
Ruby
298
star
47

stencil

Android library, written exclusively in kotlin, for animating the path created from text
Kotlin
282
star
48

Perform

Easy dependency injection for storyboard segues
Swift
280
star
49

superglue

A productive library for Classic Rails, React and Redux
JavaScript
275
star
50

upcase

Sharpen your programming skills.
Ruby
275
star
51

testing-rails

Source code for the Testing Rails book
HTML
269
star
52

proteus

[no longer maintained]
Ruby
254
star
53

Delta

Managing state is hard. Delta aims to make it simple.
Swift
246
star
54

foundry

Providing a new generation of vector assets and infinite possibility for the interactive web and mobile applications
CSS
233
star
55

limerick_rake

A collection of useful rake tasks.
Ruby
232
star
56

backbone-support

lumbar support
JavaScript
227
star
57

shoulda-context

Shoulda Context makes it easy to write understandable and maintainable tests under Minitest and Test::Unit within Rails projects or plain Ruby projects.
Ruby
219
star
58

terrapin

Run shell commands safely, even with user-supplied values
Ruby
216
star
59

Superb

Pluggable HTTP authentication for Swift.
Swift
203
star
60

jack_up

[DEPRECATED] Easy AJAX file uploading in Rails
Ruby
202
star
61

fistface

DIY @font-face web service.
Ruby
182
star
62

squirrel

Natural-looking Finder Queries for ActiveRecord
Ruby
178
star
63

sortable_table

Sort HTML tables in your Rails app.
Ruby
157
star
64

write-yourself-a-roguelike

Write Yourself A Roguelike: Ruby Edition
Ruby
155
star
65

pester

Automatically ask for a PR review
Ruby
147
star
66

jester

REST in Javascript
JavaScript
146
star
67

complexity

A command line tool to identify complex code
Rust
142
star
68

kumade

Heroku deploy tasks with test coverage (DEPRECATED, NO LONGER BEING DEVELOPED)
Ruby
137
star
69

proteus-middleman

[no longer maintained]
CSS
133
star
70

FunctionalJSON-swift

Swift
133
star
71

capybara_discoball

Spin up an external server just for Capybara
Ruby
128
star
72

tropos-android

Weather and Forecasts for Humans
Kotlin
128
star
73

ModalPresentationView

Remove the boilerplate of modal presentations in SwiftUI
Swift
125
star
74

react-native-typescript-styles-example

A template react native project for ergonomic styling structure and patterns.
TypeScript
123
star
75

vimulator

A JavaScript Vim simulator for demonstrations
JavaScript
119
star
76

bourne

[DEPRECATED] Adds test spies to mocha.
Ruby
114
star
77

formulator

A form library for Phoenix
Elixir
106
star
78

poppins

Gifs!
Objective-C
106
star
79

tailwindcss-aria-attributes

TailwindCSS variants for aria-* attributes
JavaScript
100
star
80

ghost-theme-template

A project scaffold for building ghost themes using gulp, node-sass, & autoprefixer
HTML
91
star
81

paperclip_demo

Paperclip demo application
Ruby
87
star
82

middleman-template

The base Middleman application used at thoughtbot, ready to deploy to Netlify.
CSS
86
star
83

proteus-jekyll

[no longer maintained]
CSS
84
star
84

report_card

metrics and CI are for A students.
Ruby
77
star
85

ios-sample-blender

Sample code for the Blending Modes blog post
Objective-C
76
star
86

yuri-ita

Create powerful interfaces for filtering, searching, and sorting collections of items.
Ruby
76
star
87

baccano

[no longer maintained]
HTML
74
star
88

goal-oriented-git

A practical book about using Git
HTML
73
star
89

ios-on-rails

A guide to building a Rails API and iOS app
HTML
72
star
90

art_vandelay

Art Vandelay is an importer/exporter for Rails 6.0 and higher.
Ruby
71
star
91

maybe_haskell

Programming without Null
HTML
71
star
92

redbird

A Redis adapter for Plug.Session
Elixir
67
star
93

maintaining-open-source-projects

A successful open source project is not only one that is original, solves a particular problem well, or has pristine code quality. Those are but the tip of the iceberg, which we'll thoroughly dissect with this book.
Shell
67
star
94

templates

Documentation templates for open source projects.
64
star
95

FOMObot

A slack bot to help with FOMO.
Haskell
61
star
96

BotKit

BotKit is a Cocoa Touch static library for use in iOS projects. It includes a number of helpful classes and categories that are useful during the development of an iOS application.
Objective-C
61
star
97

react-native-template

Template React Native project to be used with Cookiecutter
JavaScript
60
star
98

CombineViewModel

An implementation of the Model-View-ViewModel (MVVM) pattern using Combine.
Swift
59
star
99

flightdeck

Terraform modules for rapidly building production-grade Kubernetes clusters following SRE practices
HCL
55
star
100

design-for-developers-starter-kit

A starter project for design for developer students
CSS
54
star