はじめに
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
で下記のように記述します。
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
以上でモジュールの紹介は終わりです。
情報が足りないんじゃないか?などがあればコメントくださると嬉しいです。
参考