RailsでDeviseを試してみる

CentOSにPassenger/Ruby2.0/Rails4.0をインストールしてみる(rbenv版)
Railsの環境を構築して
CentOSにMySQL5.6をインストールしてみる
MySQLをインストールした状態。

RailsでDeviseを試してみる。

【参考】

Deep valley まとめ版 - RailsでDeviseを使ってみた
http://kitbc.s41.xrea.com/main/?use_devise

Rails4 にて Devise でユーザー登録・ログイン認証・認可の機能を追加 | EasyRamble
http://easyramble.com/devise-on-rails.html

Rails Girls - Japanese
http://railsgirls.jp/devise/

Rails - deviseの導入 - Qiita
http://qiita.com/snaka/items/a12756a5b63bd2d5e9a2

前準備

mysql-develを入れておく。

$ sudo yum -y install mysql-devel

前回作成したsampleアプリケーションを削除し、新たにmysqlに対応したsampleアプリケーションを作成する

$ rm -rf sample
$ rails new sample -d mysql

いつものごとく、therubyracerのところのコメントを外す

$ cd sample
$ vi Gemfile
gem 'therubyracer', platforms: :ruby	←コメントを外す
$ bundle install

データベースを作成する。

$ rake db:create

sample_developmentが作成されているのが確認できる。

$ mysql -u root
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sample_development |
| sample_test        |
+--------------------+

Gemのインストール

deviseのgemをインストールする。

$ vi Gemfile
gem 'devise'
$ bundle install

Deviseのセットアップ

devise:installする。
2つのファイルが作成される。

$ rails generate devise:install
      create  config/initializers/devise.rb
      create  config/locales/devise.en.yml

devise.rbには、下記のような設定がされている。

$ cat config/initializers/devise.rb
Devise.setup do |config|
  ・・・
  config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
  ・・・
  require 'devise/orm/active_record'
  ・・・
  config.case_insensitive_keys = [ :email ]
  ・・・
  config.strip_whitespace_keys = [ :email ]
  ・・・
  config.skip_session_storage = [:http_auth]
  ・・・
  config.stretches = Rails.env.test? ? 1 : 10
  ・・・
  config.reconfirmable = true
  ・・・
  config.expire_all_remember_me_on_sign_out = true
  ・・・
  config.password_length = 8..128
  ・・・
  config.reset_password_within = 6.hours
  ・・・
  config.sign_out_via = :delete
  ・・・
end

devise.en.ymlには、色々なメッセージが英語で定義されている。

$ cat config/locales/devise.en.yml
en:
  devise:
    confirmations:
      confirmed: "Your email address has been successfully confirmed."
      send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes."
      send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how
to confirm your email address in a few minutes."
    failure:
      already_authenticated: "You are already signed in."
      inactive: "Your account is not activated yet."
・・・

手順に沿って設定

devise:installをした際、下記の手順が表示される。
これに沿って設定する。

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

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', port: 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 on Heroku with Rails 3.2 only, 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.

  5. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

==============================================================================
1.

メールを送信しなければ、設定しなくても問題なさそうなので
とくに何もしないでおく。(よく分かってないが)

2.

とりあえず手順に合わせて、rootにhomeコントローラのindexを設定しておく。

$ vi config/routes.rb
・・・
  root to: "home#index"	←追加
・・・
3.

レイアウトに下記を追加する。

$ vi app/views/layouts/application.html.erb
・・・
<body>

<p class="notice"><%= notice %></p>	←追加
<p class="alert"><%= alert %></p>	←追加

<%= yield %>
・・・
4.

herokuは今のところ関係ないので、特に何もしないでおく。(よく分かってないが)

5.

viewは、とりあえず自分で用意する。

ちなみにdevise:viewsを生成すると、下記のようなファイルが生成される。

$ rails generate devise:views
      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/devise/shared
      create    app/views/devise/shared/_links.erb
      invoke  form_for
      create    app/views/devise/confirmations
      create    app/views/devise/confirmations/new.html.erb
      create    app/views/devise/passwords
      create    app/views/devise/passwords/edit.html.erb
      create    app/views/devise/passwords/new.html.erb
      create    app/views/devise/registrations
      create    app/views/devise/registrations/edit.html.erb
      create    app/views/devise/registrations/new.html.erb
      create    app/views/devise/sessions
      create    app/views/devise/sessions/new.html.erb
      create    app/views/devise/unlocks
      create    app/views/devise/unlocks/new.html.erb
      invoke  erb
      create    app/views/devise/mailer
      create    app/views/devise/mailer/confirmation_instructions.html.erb
      create    app/views/devise/mailer/reset_password_instructions.html.erb
      create    app/views/devise/mailer/unlock_instructions.html.erb

Userモデル作成

deviseでUserモデルを生成する。

$ rails generate devise User
      invoke  active_record
      create    db/migrate/20140817113503_devise_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/models/user_test.rb
      create      test/fixtures/users.yml
      insert    app/models/user.rb
       route  devise_for :users

下記のマイグレーションのファイルが生成される。

$ cat db/migrate/20140817113503_devise_create_users.rb
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

下記のUserモデルが生成される。

$ cat app/models/user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

また、routes.rbには、下記の行が追加される。

$ cat config/routes.rb
Sample::Application.routes.draw do
  devise_for :users		←追加
・・・

usersテーブル作成

マイグレーションを実行すると、

$ rake db:migrate

下記のテーブルが作成される。

$ mysql -u root
mysql> use sample_development
mysql> desc users;
+------------------------+--------------+------+-----+---------+----------------+
| Field                  | Type         | Null | Key | Default | Extra          |
+------------------------+--------------+------+-----+---------+----------------+
| id                     | int(11)      | NO   | PRI | NULL    | auto_increment |
| email                  | varchar(255) | NO   | UNI |         |                |
| encrypted_password     | varchar(255) | NO   |     |         |                |
| reset_password_token   | varchar(255) | YES  | UNI | NULL    |                |
| reset_password_sent_at | datetime     | YES  |     | NULL    |                |
| remember_created_at    | datetime     | YES  |     | NULL    |                |
| sign_in_count          | int(11)      | NO   |     | 0       |                |
| current_sign_in_at     | datetime     | YES  |     | NULL    |                |
| last_sign_in_at        | datetime     | YES  |     | NULL    |                |
| current_sign_in_ip     | varchar(255) | YES  |     | NULL    |                |
| last_sign_in_ip        | varchar(255) | YES  |     | NULL    |                |
| created_at             | datetime     | YES  |     | NULL    |                |
| updated_at             | datetime     | YES  |     | NULL    |                |
+------------------------+--------------+------+-----+---------+----------------+

確認用の画面作成

確認用の画面を作成する。

$ rails generate controller home index

viewを下記のようにする。

$ vi app/views/home/index.html.erb
<h1>Home#index</h1>

<% if user_signed_in? %>

  <!-- ユーザーがログイン中の場合 -->
  <%= debug current_user %>
  <%= link_to "ログアウト", destroy_user_session_path, method: :delete %><br />
  <%= link_to '変更', edit_user_registration_path %><br />

<% else %>

  <!-- ユーザーがログインしていない場合 -->
  <%= link_to "ログイン", new_user_session_path %><br />
  <%= link_to "登録", new_user_registration_path %><br />

<% end %>

確認

※このVirtualBox環境のIPアドレスは「192.168.56.101」。

http://192.168.56.101/
にアクセスすると、下記の画面が表示される。


登録をクリックして、メールアドレスやパスワードを入力。


登録すると、Homeに戻って、ログイン中の状態になっている。


ユーザー情報がusersテーブルに登録されているのが確認できる。

mysql> select * from users\G
*************************** 1. row ***************************
                    id: 1
                 email: test@example.com
    encrypted_password: $2a$10$r8NLPGjpYFneCDCGEfm1ser7mqC6ppYFcr2.pjgw7cFf8fuvzQHXC
  reset_password_token: NULL
reset_password_sent_at: NULL
   remember_created_at: NULL
         sign_in_count: 2
    current_sign_in_at: 2014-08-17 23:23:33
       last_sign_in_at: 2014-08-17 23:20:10
    current_sign_in_ip: 192.168.56.1
       last_sign_in_ip: 192.168.56.1
            created_at: 2014-08-17 23:20:10
            updated_at: 2014-08-17 23:23:33

ログアウトすると、ログインしていない状態に戻る。


ログインすると、


再びログイン中の状態になる。


他にも色々機能がある。

変更画面を表示すると、メールアドレスやパスワードなど変更できる。


パスワードを忘れた時のための画面もある。