【Rails】deviseのメール認証を使えるようにする(Confirmable)・ローカル編

初めに

業務でdeviseのメール認証(Confirmable)を使っていますが、自分でメール認証の設定をしたことがないためアウトプットします。

今回はローカルで動かすところまでやってみます。

ローカルのメール確認にはletter_openerを使用。

手順

deviseのインストール

gem 'devise'

group :development do
  # letter_openerも入れておきます
  gem 'letter_opener'
end
bundle install

# deviseのインストール
rails g devise install

devise日本語化

config/locales/devise.ja.ymlに翻訳ファイルを配置しておきます。

curl -s https://raw.githubusercontent.com/tigrish/devise-i18n/master/rails/locales/ja.yml -o config/locales/devise.ja.yml

メール認証の設定

Userモデル作成

rails g devise user

confirmabaleカラムの有効化

Userモデルを作成時に自動生成されたマイグレーションファイルのConfirmableの箇所のコメントアウトを外す。

# frozen_string_literal: true

class DeviseCreateUsers < ActiveRecord::Migration[7.0]
  def change
    create_table :users do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      # (省略)

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

      # (省略)

  end
end
# マイグレートします
rails db:migrate

モデルの設定変更

:confirmableを追記

# confirmableを追記
class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :confirmable
end

# メールの送信元を設定
config.mailer_sender = 'makky@example.com'

Mailerの設定

config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.delivery_method = :letter_opener

flashの設定

deviseから提供されるフラッシュメッセージを表示するようにしておきましょう。

cssにbootstrap使っています。(ここではbootstrapの導入は説明しません。)

- flash.each do |type, message|
  = content_tag(:div, message, class: "alert alert-#{type == 'notice' ? 'success' : 'danger'}")

動作確認

ユーザー一覧には最初何もなし


http://localhost:3000/users/sign_up にてサインアップ


サインアップ後、メールが送信される


画面にはフラッシュメッセージが表示


本人確認が完了していない状態(メールのリンクを踏んでいない状態)でログインしてみる


本人確認が必要とフラッシュメッセージが表示


メールのリンクから遷移すると、メールアドレスの確認が完了する


ログインが問題なくできるようになる


終わりに

今回はローカルでdeviseのメール認証を使えるようにしてみました。

次は本番環境でどう使うのかアウトプットしてみようと思います。

また、メールアドレスのみでサインアップをし、メールのリンクを踏んだらパスワード入力→そのままログインもやってみたいと思います。