본문으로 건너뛰기

기술 글

reCAPTCHA 적용하기

외부로 노출된 문의하기, 메일쓰기, 회원가입의 경우 봇에의해 자동 입력...

표시 날짜
읽는 시간
1 min read
Tags

외부로 노출된 문의하기, 메일쓰기, 회원가입의 경우 봇에의해 자동 입력이 이뤄지는 경우가 있습니다. 이런 경우 가장 쉽게 방지 할 수 있는 방법으로 reCAPTCHA가 있습니다.

구글 reCAPTCHA 에서 자세한 정보를 확인할 수 있습니다.

gem recaptcha를 사용해 구현했습니다.

Gem 설치

    gem "recaptcha"

키 등록

reCAPTCHA Site key 와 Secret key가 필요하고 홈페이지에서 발급 가능합니다. initializers/recaptcha.rb에 키 정보를 넣어주세요

Recaptcha.configure do |config|
  config.site_key  = 'SITE_KEY'
  config.secret_key = 'SECRET_KEY'
end

적용하기

reCAPTCHA가 필요한 form에 아래와 같이 한 줄만 추가하면 사용 가능합니다.

<%= form_for @foo do |f| %>
  # …
  <%= recaptcha_tags %>
  # …
<% end %>

컨트롤러에서는 verify_recaptcha함수를 통해 성공, 실패 여부를 확인할 수 있습니다.

## app/controllers/notice_controller.rb
@notice = Notice.new(notice_params)
if verify_recaptcha(model: @notice) && @notice.save
  redirect_to @notice
else
  render 'new'
end

Devise 회원가입에 적용하기

devise에 적용하는 방법

registration/new.html.erb

  <%= recaptcha_tags %>

컨트롤러는 먼저 registration controller를 재정의 해야합니다.

rails g devise:controllers users -c=registrations
## app/controllers/registrations_controller.rb 파일 생성

config/foutes.rb파일에 추가합니다.

devise_for :users, controllers: { ... , registrations: "registrations", ... }

다시 registrations_controller로 돌아와 아래 코드를 추가하면 됩니다.

class RegistrationsController < Devise::RegistrationsController
  prepend_before_action :check_captcha, only: [:create] # Change this to be any actions you want to protect.

  private
    def check_captcha
      unless verify_recaptcha
        self.resource = resource_class.new sign_up_params
        resource.validate # Look for any other validation errors besides Recaptcha
        set_minimum_password_length
        respond_with_navigational(resource) { render :new }
      end
    end
end