본문 바로가기

Ruby on Rails

Devise로 이메일 인증 구현하기

환경

  • 루비 버전    : ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin17]
  • 레일즈 버전 : Rails 5.1.6

구현

필요한 잼은 두가지이다.

  • Devise 버전 : 4.4.3
  • mailgun 버전 : 1.1.6

인스톨을 하고 디바이스로 유저를 생성한다.


$ rails g devise User



가장 먼저 모델(여기서는 User)에 confirmable 을 추가해준다.


class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
end





이제 유저 마이그레이션 파일을 보면 confirmable에 대한 부분이 주석처리 되어 있는 것을 볼 수 있다. 해당 부분의 주석을 제거해준다.

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



이제 마이그레이션을 해준다.



$ bin/rake db:migrate





그 다음 https://www.mailgun.com  해당 홈피에 들어가 가입한다. 도메인 없이 300개 무료 이메일을 발송해준다.


가입하면 이렇게 메일 전송 도메인을 획득할 수 있다.






상단 네비게이션 바에서 Account  Settings > Authorized Recipients 선택해서 보낼 이메일 주소를 적는다.

이메일로 이동해서 인증하면 준비완료





그다음 config/environments/development.rb 로 이동해서 아래의 내용을 적어 준다.


config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: 'fb0XXXXXXXXXXXXXXXXXXXXXX-3XXXXXXXf-5XXXXXX2',
domain: 'sandboxHAHAHAHAHAHAHAHAHAHAc6b4e.mailgun.org',
}

config.action_mailer.default_url_options = { host: 'localhost:3000' }



Delivery_method와 mailgun_settings는 사용할 메일링 API의 정보이다. 하단의 default_url_options 는 확인 이메일에 붙을 도메인주소를 위해 사용된다. 아래와 같이 적으면 테스트 환경에서도 링크를 클릭하여 인증이 가능하다. 만일 포트를 변경하여 서버를 올렸다면 해당 포트를 변경해주도록


프로뎍션 환경도 동일하다. default_url_options를 본인의 도메인으로 변경하면 된다.