LoginSignup
1
0

More than 3 years have passed since last update.

[Rails]deviseのモジュールについて

Posted at

はじめに

deviseを自作のRailsアプリケーションで使用したので備忘録ととして残しておきます。
今回はdeviseで定義されているモジュールについて記述していきます。

deviseの導入方法は以下を確認ください
[Rails] devise導入方法

モジュールの説明

マイグレーションファイルを確認すると以下のようになっています。

class DeviseCreateUsers < ActiveRecord::Migration[6.0]
  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.inet     :current_sign_in_ip
      t.inet     :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

「#」が2つ付いているところがモジュール名になります。

これを上から順に説明していきます。

1.DatabaseAuthenticatable
データベースに保存されたパスワードが合っているか検証をします。
同時にパスワードの暗号化も行う。

2.Recoverable
パスワードリセットを行います。

3.Rememberable
クッキーにログイン情報を保持します。

4.Trackable
ログインした回数、最終ログイン日時、前回ログイン日時、最終ログインIP、前回ログインIPを保存する。

5.Confirmable
新規登録時によるメール認証機能の付加。

6.Lockable
ログインに何度も失敗すると、アカウントをロックする。
何回失敗するとロックするかはLockable内で指定できる。

その他のモジュール

マイグレーションファイルに記述されている以外にもモジュールが用意されています。
7.Timeoutable
ログインしたままの状態で一定時間経つと自動でログアウトさせます。
デフォルトだと30分になっています。

8.Registerable
登録処理を通してユーザーをサインアップします。また、ユーザーに自身のアカウントを編集したり削除することを許可します。

9.Validatable
Emailやパスワードのバリデーションを追加する。独自に定義したバリデーションを追加することもできます。

omniauthable
twitterやFacebookなどのSNS認証を追加します。

モジュールの使い方

モジュールを使う場合はapp/models/users.rbで下記のように記述します。

app/models/users.rb
devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :validatable

以上でモジュールの紹介は終わりです。
情報が足りないんじゃないか?などがあればコメントくださると嬉しいです。

参考

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