Skip to content

Authenticate with username

Justin Tomich edited this page May 17, 2017 · 3 revisions

Authenticate can use :username, rather than :email, to sign up and sign in. However, :username is not desirable for most situations, thus Authenticate defaults to :email.

Why Not Username?

Your email address is a unique identifier. Usernames tend to be taken; a user tries to sign up and their username is already taken, leading to user frustration and a lower conversion rate. This doesn't happen when you register with email addresses. Most applications are better off with registering with email addresses.

How to switch to username

Authenticate ships with username support, but you'll have to take a few manual steps. This guide assumes you've already installed authenticate.

Add the username column to user

You'll have to manually add the username column to your user model.

rails generate migration AddUsernameToUsers username:string:uniq
rake db:migrate

Config

Set config.authentication_strategy = :usernmame, like so:

# config/initializers/authenticate.rb
Authenticate.configuration do |config|
  config.authentication_strategy = :usernmame
end

Views

The default Authenticate views assume email address, but you can implement username with a few custom tweaks.

Copy the default authenticate views into your app with Authenticate's view generator:

r g authenticate:views

Edit session/new.html.erb, and switch :email to :username, example:

<div class="field">
  <%= form.label :username %>
  <%= form.text_field :username %>
</div>

Edit users/new.html.erb, add the username field above the email field:

<div class="field">
  <%= form.label :username %>
  <%= form.text_field :username %>
</div>

<div class="field">
  <%= form.label :email %>
  <%= form.text_field :email, type: 'email' %>
</div>

<div class="field">
  <%= form.label :password %>
  <%= form.password_field :password %>
</div>

Now restart your app and test. You shouldbe be creating users with username, email, and password, and authenticating with username and password.