divise 3.2.0 + Ruby on Rails 4.0 でusernameを認証に使用する

devise3.2.0 + Ruby on Rails 4.0でusernameを使用した認証の話.
deviseについてはこちらを参照.
作りたいものはtwitterのように登録時はemail+username+passwordでログイン時はusername+passwordでログインできるもの.

deviseをインストール

まずはdeviseをrailsに入れる.Gemfileに追記

gem 'devise'

その後

$ bundle install

deviseをインストール.

$ bundle exec rails g devise:install

deviseの環境設定

config/environments/development.rbに以下を追加

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

config/routes(appはコントローラ名)に追加

root to: "app#index"

app/views/layouts/application.html.erbの好きなところに追加

<p class="notice"><%= notice %></p>
<p class="alert"><%= alert %></p>

deviseで使用するテーブルの設定

deviseで使用するテーブルををかく.(今回はuser)

$ bundle exec rails g devise user

usernameで認証したいのでテーブルにusernameを増やす

$ bundle exec rails generate migration add_username_to_users username:string

その後migrateする

$ bundel exec rake db:migrate

以上でテーブルはできる.

deviseのviewの設定

とりあえず以下を実行してapp/views/deviseにviewを作成

rails generate devise:views

また,今回はusernameを認証に使用するのでapp/views/devise/sessions/new.html.erbを書き換える

<!-- 変更前 -->
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true %></div>

 <!-- 変更後 -->
<div><%= f.label :username %><br />
<%= f.text_field :username, :autofocus => true %></div>

登録フォームはusername+email+passwordを使えるように/app/views/devise/registrations/new.html.erbに以下を追加(emailのあとくらいに)

<div><%= f.label :username %><br />
<%= f.text_field :username, :autofocus => false %></div>

アカウント編集も登録と同じように/app/views/devise/registrations/edit.html.erbに以下を追加(emailのあとくらいに)

<div><%= f.label :username %><br />
<%= f.text_field :username, :autofocus => false %></div>

usernameを使えるようにする

app/controllers/application_controller.rbを書き換える

class ApplicationController < ActionController::Base
  before_filter :configure_permitted_parameters, if: :devise_controller?
  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_in) << :username
    devise_parameter_sanitizer.for(:sign_up) << :username
    devise_parameter_sanitizer.for(:account_update) << :username
  end
end

config/initializers/devise.rbconfig.authentication_keys = [ :email ]がコメントアウトされてるので以下に書き換える

config.authentication_keys = [ :username ]

後はlocalhost:3000/app/users/sign_upでユーザ作ったのち一度ログアウトしてlocalhost:3000/app/users/sign_inでusernama+passwordでログインできるか確認する.
以上です.

参考URL

ASCIIcasts - “Episode 210 - Deviseのカスタマイズ”
devise:strong-parameters
deviseのRails4.0.0対応に関して