悪あがきプログラマー

悪あがきを続けていきたい技術と書評なブログです。トレタでiOSエンジニアやってます。

Railsアプリにユーザー認証を!Deviseを使ってみる

WEB+DB PRESSのRubyわくわくナビ第5回に載ってたライブラリを色々試していこうかと思います

その第一弾

Devise
https://github.com/plataformatec/devise
ここに書いてあるとおりにやっていきます

Getting started

Gemfile

gem 'devise'

bundle実行

MBP13:wakuwakunavi yoonchul$ bundle install

railsアプリにdeviseをインストール

MBP13:wakuwakunavi yoonchul$ rails generate devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml
===============================================================================

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here 
     is an example of default_url_options appropriate for a development environment 
     in config/environments/development.rb:

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

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root :to => "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

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

  4. If you are deploying Rails 3.1 on Heroku, you may want to set:

       config.assets.initialize_on_precompile = false

     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.

===============================================================================

ふむ、これらは自動でやってくれないと

  1. メール設定しましょう
    • サインアップの確認とかでメール投げるからね
  2. ホームを設定しましょう
    • これはエラー時とかの飛ばし先かな
  3. flashメッセージの追加
    • 各種メッセージを出すわけですね
  4. Herokuにあげるならassetsのprecompileはoffにしておきましょう。
    • なんでや?

とりあえず上記を言われたとおりに設定する。

次にモデルを生成
モデル名はとりあえずUserで

MBP13:wakuwakunavi yoonchul$ rails g devise User
      invoke  active_record
      create    db/migrate/20120229114625_devise_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/unit/user_test.rb
      create      test/fixtures/users.yml
      insert    app/models/user.rb
       route  devise_for :users

続いてmigrate

MBP13:wakuwakunavi yoonchul$ rake db:migrate
==  DeviseCreateUsers: migrating ==============================================
-- create_table(:users)
   -> 0.0174s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0010s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0007s
==  DeviseCreateUsers: migrated (0.0208s) =====================================

確認用に適当なhomeコントローラーを作ります
rootに設定しているのでpublic/index.htmlを消すのも忘れずに

MBP13:wakuwakunavi yoonchul$ rails g controller home index
      create  app/controllers/home_controller.rb
       route  get "home/index"
      invoke  erb
      create    app/views/home
      create    app/views/home/index.html.erb
      invoke  test_unit
      create    test/functional/home_controller_test.rb
      invoke  helper
      create    app/helpers/home_helper.rb
      invoke    test_unit
      create      test/unit/helpers/home_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/home.js.coffee
      invoke    scss
      create      app/assets/stylesheets/home.css.scss
MBP13:wakuwakunavi yoonchul$ rm public/index.html 

Controller filters and helpers

さて、いよいよ認証の設定

認証をかけたいところに下記before filterを追加

before_filter :authenticate_user!

今回の場合はHomeControllerに追加

class HomeController < ApplicationController
  before_filter :authenticate_user!         
  def index
  end
end

これで、http://0.0.0.0:3000/にアクセスすると、

認証が必要なためhttp://0.0.0.0:3000/users/sign_inにリダイレクトされました!
f:id:y_koh:20120229210106p:plain

下にあるSign upを押下するとSign up画面に切り替わります
f:id:y_koh:20120229210655p:plain

必要事項を入力してSign upボタンを押下するとSign upが完了します
f:id:y_koh:20120229210954p:plain

いやぁ、簡単ですね

ちなみにSign outに関しては
同じように/users/sign_outにアクセスすればいいんですけど、
deleteメソッドでアクセスする必要があるとのことなので、Sign outはこうやってリンクを作成しちゃいましょ

<%= link_to "Sign out",  destroy_user_session_path,  :method => :delete %> 

これをlayouts/application.html.erbのbodyタグ直下にでも置けば画面上部にSign outが出てきます
押下するとちゃんとSign outできた!
f:id:y_koh:20120229212522p:plain