How to sign up and sign in with user name
Clone this wiki locally
One of the design decisions in Clearance is the lack of a username. Clearance dictates an email address & password are used for authentication.
Your email address is a unique identifier. Requiring users to create an additional username for authentication is inviting the following headaches:
- I sign up for your new web app & request the username “Croaky”.
- It’s taken. Aggravated, I try “dancroak”, my other most common username.
- It’s taken! Now I try “dancroak13” or “lawless” or some other uncommon, less-memorable name.
- A month goes by. I return to sign in & have no idea what username I used.
Not all web apps using authentication need a username, but some do. Consider Twitter: your username is a crucial part of the system.
While Clearance will never include the username feature, it is flexible enough for you to add this feature to your app.
How to add username sign in
Here are the general steps:
- Don’t change the sign in form’s text fields. Only change the label for the email field to read “Email or username”.
- Test UsersController#new includes a username (or “handle” or whatever) text field.
- Watch the test fail, then add the field to your form.
- Test UsersController#create creates a User with a username of the given parameter.
- Watch it error because the User does not have a username attribute.
- Write a migration that adds username to User.
- Run the UsersController#create test again.
- Watch it fail because the User model is using attr_accessible.
- Test the User model using should_validate_presence_of :username & should_allow_mass_assignment_of :username
- Watch that test fail, then add :username to the attr_accessible white list.
- Run the UsersController#create test again. It should pass now.
- Test SessionsController#create that given a User’s username for the :email value, the User should be signed in.
- Run it, watch it fail because the authenticate method only checks email attribute.
- Add a test to your user_test file that the authenticate method can use :username with password.
- Watch it fail, then alter the authenticate method until it passes.
- All tests should now pass & the feature is implemented.
Mihai Anca wrote an example app & maintains it at ropiku/clearance-username