LoginSignup
1
4

More than 5 years have passed since last update.

Deviseでメール認証をできるようにする

Posted at

Deviseでメール認証を実装する

前提条件

  • Deviseの基本的な使用方法はわかっている
    • メール認証なしの時との差分だけ書きます。
  • Gmailを使用
    • 今回は独自ドメインで利用しています。
  • とりあえずローカルだけで、本番では試してません。

ソースコードの変更箇所

以下の記述を追記

app/models/deivseを使っているモデルのファイル
devise :database_authenticatable,:registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable

新規でモデルを作るのか、後からメール認証を付けるかで変わりますが...
新規の場合は下記の行のコメントアウトを解除します。

マイグレーションファイル
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable
config/environments/development.rb
config.action_mailer.default_url_options = {  host: 'localhost', port: 3000 }
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address: 'smtp.gmail.com',
    port: '587',
    domain: '独自ドメイン',
    user_name: 'メールアドレス',
    password: 'アプリパスワード', # 詳細は後ほど
    authentication: :plain,
    enable_starttls_auto: true
  }

productionのときはproduction.rbもよしなに変更したらいいと思います(未確認)

Gmailの設定変更箇所

何も設定せずにやると、安全性の低いアプリと認識されて認証されません。
解除方法は、

  • 安全性の低いアプリのログインを許可
  • 2段階認証を登録してアプリ固有のパスワードを登録

前者が上手く行かなかったので後者にしました。

2段階認証の設定
アプリパスワードの設定

config/environments/development.rbでは使うメールアドレスのパスワードではなく、ここで指定されたアプリパスワードを使ってください。

おわり

これでとりあえず動きました!
Gmailの設定周りを全く知らずに結構時間食いました。

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