DeviseでSign up時にメール確認する
前回の続いてメール確認を実装します。
前回のエントリー
Railsアプリにユーザー認証を!Deviseを使ってみる - 悪あがきプログラマー
今回はAdminモデルを作ります
MBP13:wakuwakunavi yoonchul$ rails g devise Admin
invoke active_record
create db/migrate/20120229143303_devise_create_admins.rb
create app/models/admin.rb
invoke test_unit
create test/unit/admin_test.rb
create test/fixtures/admins.yml
insert app/models/admin.rb
route devise_for :admins
メール確認を有効にするために、生成されたmigrationファイルの下記部分をコメントアウトします
25 ## Confirmable 26 t.string :confirmation_token 27 t.datetime :confirmed_at 28 t.datetime :confirmation_sent_at 29 t.string :unconfirmed_email # Only if using reconfirmable
またモデルに:confirmableを追加します
class Admin < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
今回は確認用にmanageというコントローラを作ります
MBP13:wakuwakunavi yoonchul$ rails g controller manage index
create app/controllers/manage_controller.rb
route get "manage/index"
invoke erb
create app/views/manage
create app/views/manage/index.html.erb
invoke test_unit
create test/functional/manage_controller_test.rb
invoke helper
create app/helpers/manage_helper.rb
invoke test_unit
create test/unit/helpers/manage_helper_test.rb
invoke assets
invoke coffee
create app/assets/javascripts/manage.js.coffee
invoke scss
create app/assets/stylesheets/manage.css.scss
before filterを追加します
class ManageController < ApplicationController before_filter :authenticate_admin! def index end end
これでhttp://0.0.0.0:3000/manage/indexにアクセスすると、
http://0.0.0.0:3000/admins/sign_inにリダイレクトされました

ここでSign upすると確認メールが送信されます
と言ってもメールサーバーは立ってないし、
メール送信自体の設定はしていないのでログに出てくるだけです
この状態ではまだログインできません
Sent mail to xxxxxxxxxxx@gmail.com (104ms) Date: Thu, 01 Mar 2012 21:53:02 +0900 From: please-change-me-at-config-initializers-devise@example.com Reply-To: please-change-me-at-config-initializers-devise@example.com To: xxxxxxxxxxxxx@gmail.com Message-ID: <4f4f712ec76d7_38673fe11b015c481966c@MBP13.local.mail> Subject: Confirmation instructions Mime-Version: 1.0 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: 7bit <p>Welcome xxxxxxxxxxxx@gmail.com!</p> <p>You can confirm your account email through the link below:</p> <p><a href="http://localhost:3000/admins/confirmation?confirmation_token=1J77Qy3VTopr3iXo9AkT">Confirm my account</a></p>
一番下のConfirm my accountのリンク先にアクセスするとメール確認が完了し、
ログインできます

ちなみにもう一度同じ確認URLにアクセスすると、、

ちゃんとはじかれてます
いやぁ便利ですね!