前回まではビュー側のbot対策をしました。
今度はコントローラー側の対策をしていきます!
コントローラーをbot対策する
さて、次はサーバー側をbot対策します。
Recaptchに書いてるあることはこんな感じです
つまり、
https://www.google.com/recaptcha/api/siteverify
にシークレットキーとレスポンスをセットして、POSTリクエストを送ればいい訳ですね。
(今回はRailsにライブラリ入ってましたが、JavaでやるときはGoogleが配布しているライブラリが必要です。
Spring IOとかで管理されていないので、Googleからダウンロード
https://developers.google.com/recaptcha/old/docs/java
)
POST用のクライアントソフトをGemに入れる
まずはPOSTリクエストを送るGemを導入します。
gem 'lograge', '~> 0.10'
gem 'redis-rails', '~> 5.0'
end
gem 'faraday'
Gemfile.lock
dotenv-rails (~> 2.2, < 2.3)
fabrication (~> 2.20)
faker (~> 1.8)
faraday <-これを追加
fast_blank (~> 1.0)
fastimage
fog-core (~> 1.45)
コントローラーを編集する。
次に、登録のアクセスを受け取った時に、
RecaptchaにPOSTリクエストを送ります。
例外を作ってbotを排除
registrations_controller.rb
def destroy
not_found
end
def create
raise 'Only human can register our service.' unless is_human?
super
end
protected
def update_resource(resource, params)
params[:password] = nil if Devise.pam_authentication && resource.encrypted_password.blank?
@@ -91,8 +94,28 @@ def set_invite
def determine_layout
%w(edit update).include?(action_name) ? 'admin' : 'auth'
end
concerning :RecaptchaFeature do
if ENV['RECAPTCHA_ENABLED'] == 'true'
def is_human?
g_recaptcha_response = params["g-recaptcha-response"]
return false unless g_recaptcha_response.present?
verify_by_recaptcha g_recaptcha_response
end
def verify_by_recaptcha(g_recaptcha_response)
conn = Faraday.new(url: 'https://www.google.com')
res = conn.post '/recaptcha/api/siteverify', {
secret: ENV['RECAPTCHA_SECRET_KEY'],
response: g_recaptcha_response
}
j = JSON.parse(res.body)
j['success']
end
else
def is_human?; true end
end
def set_sessions
end def set_sessions
@sessions = current_user.session_activations
end
end
完了!
これでbot対策が出来ました!
参考
作ったソース
https://github.com/shibafu/DakyuMastodon/
コミット履歴
https://github.com/shibafu/DakyuMastodon/commits/master