Authentication is a common pattern in Rails apps. Thus, there have been many
authentication plugins. We’ve tried acts_as_authenticated
and
restful_authentication
over
the years.
We found that user authentication is hard to generalize. Most abstracted authentication plugins had both too much and too little for us.
We then tried writing authentication from scratch on our clients’ Rails apps for about a year. We felt better about test coverage but it was still a pain to re-write similar code. App after app, we talked about extracting common code into a library. Each time we resisted.
After a while, we thought that maybe 60% of authentication could be re-used. We extracted Hoptoad’s authentication, then merged code from two of our clients’ apps. We named the gem Clearance.
On the first attempt, we went overboard on re-use. We backed off and wrote hooks in places we were finding logical extension points. For the past few months, patches have trickled in from Github and we’ve carefully included code that fits in the “60%”.
We recently started a new project. In the process, we’ve polished the gem and are happy to announce its official release.
Clearance
- Sign up
- Confirm email
- Sign in
- Sign out
- Reset password
Get it on Github.
Modules, Shoulda, and Factory Bot
Clearance is focused on maintainability of your application’s authentication code.
- Include comprehensive Shoulda and Factory Bot tests in your Rails app’s test suite
- Encapsulate authentication logic in modules which are included in your controllers, models, and tests.
This approach keeps your Rails application’s code clean and alerts you if you ever break your authentication code.
Due to the work we’ve been doing to make Shoulda test framework-agnostic, you will be able to use RSpec in the 0.5.0 release of Clearance.
Test::Unit and Cucumber features are also supported:
script/generate clearance
script/generate clearance_features
Conventions
To keep our approach simple, we made a series of design decisions:
- User model required.
- User model uses attr_accessible.
- Authenticate by email (not username) and password.
- Vocabulary restricted to a trinity: “sign up”, “sign in”, “sign out”
Beyond
Clearance does not try to be a Swiss Army knife but it does have some hooks if you want admin roles, sign up and sign in by username in addition to email, or something else.
Please report bugs and request features on GitHub Issues.