Deviseを使ってユーザー認証機能をつける

提供: sha.ngri.la
移動先: 案内検索

インストール

Gemfileを編集

gem "devise"

bundle install

$ bundle install

rails g devise:install

$ rails g 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: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.

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

       rails g devise:views

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

rails g devise user

$ rails g devise user
$ rails g devise:views

app/models/user.rb

ユーザー登録の際に入力したメールアドレスにメールを送って確認するために、:confirmable を deviseの行に追加する。

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  # :registerable,
  devise :database_authenticatable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body
  
  has_many :bukumas, :dependent => :destroy
end

テスト環境でメールの送信できない場合は、ログに表示されたurlを直接開けば認証できます。

このメールはパスワード忘れた時の再登録用です。

おそらく、WEBrick Server使っているでしょうから、http://localhost:3000/users/password/edit?reset_password_token=upy7V8UMLuMbjBR9jieeにアクセスすれば、認証されます。

Sent mail to 
Date: 
From: please-change-me-at-config-initializers-devise@******.com
Reply-To: please-change-me-at-config-initializers-devise@*****.com
To: 
Message-ID: <533eeb192f62c_171f3fc772561f9892665@yaal.private.mail>
Subject: Reset password instructions
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<p>Hello </p>

<p>Someone has requested a link to change your password. You can do this through the link below.</p>

<p><a href="http://localhost/users/password/edit?reset_password_token=upy7V8UMLuMbjBR9jiee">Change my password</a></p>

<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>

db/migrate/**************_devise_create_users.rbを編集

次の部分のコメントをはずす

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

rake db:migrate

$ rake db:migrate

この辺りでサーバをリスタート(ctrl-c,rails s)しないと、アクセスしてもエラーになる。

app/controllers/****.controller.rb(****は、認証したいコントローラー)に berfore_filter :authenticate_user! を追加する。

class ****Controller < ApplicationController
  before_filter :authenticate_user!, :except => [:index, :show]

ログイン中だけ表示させたい項目、例えば new のボタンなら、app/views/モデル名/inde.html.erb 等の次の部分を編集

<% if user_signed_in? -%>
  <%= link_to t('.new', :default => t("helpers.links.new")),
              new_article_path,
              :class => 'btn btn-primary' %>
<% end %>

deviseの各機能へのリンク

ログインのリンク

<%= link_to "login", user_session_path %>

ユーザー情報の編集ページへのリンク

ログイン中のユーザーのメールアドレスを表示するのは、current_user

<%= link_to current_user.email, edit_user_registration_path %>

ログアウトするためのリンク

<%= link_to "logout", destroy_user_session_path, method: :delete %>

具体的なurlは、/users/sign_in

Link