0
0

More than 1 year has passed since last update.

deviseの導入

Posted at

https://github.com/heartcombo/devise
公式サイトより、Getting startedを参考にしながらdeviseを導入してみました。

gemファイルに追記、bundle installを実行

gem 'devise'

次に、以下のコードを実行

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', 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. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

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

何を言っているかというと、

1、メール送信についての説明
2、ルーティングについての説明
3、フラッシュについての説明
4、「rails g devise:viewsを実行したらdeviseに必要なviewファイルを用意してあげるよ」とのこと

今回は認証機能だけを実現したいので説明に従って、rails g devise:viewsを実行してみる

すると、以下のように大量のビューファイルが作成される。

   invoke  Devise::Generators::SharedViewsGenerator
   create    app/views/devise/shared
   create    app/views/devise/shared/_links.html.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/email_changed.html.erb
   create    app/views/devise/mailer/password_change.html.erb
   create    app/views/devise/mailer/reset_password_instructions.html.erb
   create    app/views/devise/mailer/unlock_instructions.html.erb

次にUserモデルを作成する。ただし、devise用に作成するため、コードに注意

rails g devise User

以下のモデルが作成される。

   invoke  active_record
   create    db/migrate/20180925032152_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

migrationファイルを見ると、ログインなどに必要な項目を既に用意してくれています。

# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[6.1]
  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 null: false
    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

特に問題なさそうなので、rails db:migrateして、サーバーを起動後、sign_upページへ移動すると、サインアップ、ログインなどできるようになっています。

deviseは認証機能に加えて、ヘルパーも提供してくれます。
かなりたくさんあるので、頻繁に使用するものだけまとめました。

ユーザー認証

メソッド名 機能
sign_in すでに認証されているユーザーでサインインする(ログイン)
sign_out 特定のユーザーまたはスコープをサインアウトする(ログアウト)
authenticate_user! ユーザーの認証を行い、ログイン済ユーザーのみにアクセスを許可する
user_signed_in? ユーザーがログインしているかどうか
current_user 現在、ログインしているユーザーのモデルインスタンスを取得する
user_session ユーザーのセッション情報を設定・取得

他にもたくさんあるので、以下をみるとコメントアウト付きで説明付きでわかりやすいです。
https://github.com/heartcombo/devise/tree/dfbed22cee617992e5f846fdef58b724b6b32ff9/lib/devise/controllers

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0