LoginSignup
1
2

More than 3 years have passed since last update.

【初心者】deviseの使い方 導入から設定変更

Last updated at Posted at 2020-06-24

はじめに

勉強のためにdeviseを使い、ログイン周りを作成しました。
デフォルトではユーザー名、パスワードで認証しますが、今回社員番号、パスワードで認証するよう設定を変更していきます。

環境

Ruby 2.5.3
Ruby on Rails 5.2.4
Devise 4.7.1

完成

スクリーンショット 2020-06-24 16.00.39.png
スクリーンショット 2020-06-24 16.00.56.png
bootstrapで見た目を整えていますが、このようになるように設定を変更していきます。

実装

Gemfile
gem 'devise'
$ bundle install

●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: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.新規登録など認証メールを送った際に、メールの文中にある承認リンクURLを設定します。

config/environments/development.rb
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

2.ルート設定
会員登録後などにルートに飛ぶ設定になっています。

3.フラッシュメッセージを埋め込みます。ログイン、ログアウトの際にフラッシュを表示させたい時に使用します。私は共通ビューに埋め込みました。

app/views/layouts/application.html.erb
<body>
 <p class="notice"><%= notice %></p>
 <p class="alert"><%= alert %></p>
</body>

4.ビューのカスタマイズをするために

$ rails g devise:views

●deviseの設定変更

config/initializers/devise.rb
43行目あたり
認証キーは社員番号を指定
- config.authentication_keys = [:email]
+ config.authentication_keys = [:employee_number]
55行目あたり
認証キーの値は大文字小文字を区別しない
- config.case_insensitive_keys = [:email]
+ config.case_insensitive_keys = [:employee_number]
60行目あたり
空白キーを取り除く
- config.strip_whitespace_keys = [:email]
+ config.strip_whitespace_keys = [:employee_number]

●ユーザーモデルを作る

$ rails g devise user
app/models/user.rb
# 以下3つのメソッドは、user名を認証キーとするので、
# 不必要なメソッドをオーバーライドして無効化しています。

def email_required?
    false
  end

  def email_changed?
    false
  end

  def will_save_change_to_email?
    false
  end

db/migrate/日付_devise_create_user.rb

class DeviseCreateUsers < ActiveRecord::Migration[5.2]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :employee_number,    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, :employee_number,      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

●コントローラーの変更

application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  # methodをオーバーライドする。
  def configure_permitted_parameters
    sign_up_params = [:employee_number, :password, :password_confirmation]
    sign_in_params = [:employee_number, :password, :remember_me] 

      # account_update, sign_in, sign_up, のフィールドを再定義
    devise_parameter_sanitizer.permit(:sign_up, keys: sign_up_params)
    devise_parameter_sanitizer.permit(:sign_in, keys: sign_in_params)
    devise_parameter_sanitizer.permit(:account_update, keys: account_update)
  end
 end

設定はこれで終わりです。あとはviewを変更すれば完成です。

参考

[Rails] deviseの使い方(rails5版)
Ruby on Rails 初心者が gem Devise 使ってみた。

1
2
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
1
2