2022-01-24 10:06:19 -08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module CaptchaConcern
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
include Hcaptcha::Adapters::ViewMethods
|
|
|
|
|
|
|
|
included do
|
2022-01-25 14:56:57 -08:00
|
|
|
helper_method :render_captcha
|
2022-01-24 10:06:19 -08:00
|
|
|
end
|
|
|
|
|
|
|
|
def captcha_available?
|
|
|
|
ENV['HCAPTCHA_SECRET_KEY'].present? && ENV['HCAPTCHA_SITE_KEY'].present?
|
|
|
|
end
|
|
|
|
|
|
|
|
def captcha_enabled?
|
2022-01-25 14:56:57 -08:00
|
|
|
captcha_available? && Setting.captcha_enabled
|
2022-01-24 10:06:19 -08:00
|
|
|
end
|
|
|
|
|
2022-01-25 13:37:12 -08:00
|
|
|
def captcha_user_bypass?
|
2022-01-25 14:56:57 -08:00
|
|
|
false
|
2022-01-25 13:37:12 -08:00
|
|
|
end
|
|
|
|
|
2022-01-24 10:06:19 -08:00
|
|
|
def captcha_required?
|
2022-01-25 14:56:57 -08:00
|
|
|
captcha_enabled? && !captcha_user_bypass?
|
2022-01-24 10:06:19 -08:00
|
|
|
end
|
|
|
|
|
|
|
|
def check_captcha!
|
|
|
|
return true unless captcha_required?
|
|
|
|
|
|
|
|
if verify_hcaptcha
|
2022-01-24 12:29:50 -08:00
|
|
|
true
|
2022-01-24 10:06:19 -08:00
|
|
|
else
|
|
|
|
if block_given?
|
|
|
|
message = flash[:hcaptcha_error]
|
|
|
|
flash.delete(:hcaptcha_error)
|
|
|
|
yield message
|
|
|
|
end
|
2022-01-24 12:29:50 -08:00
|
|
|
false
|
2022-01-24 10:06:19 -08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def extend_csp_for_captcha!
|
|
|
|
policy = request.content_security_policy
|
|
|
|
return unless captcha_required? && policy.present?
|
|
|
|
|
|
|
|
%w(script_src frame_src style_src connect_src).each do |directive|
|
|
|
|
values = policy.send(directive)
|
|
|
|
values << 'https://hcaptcha.com' unless values.include?('https://hcaptcha.com') || values.include?('https:')
|
|
|
|
values << 'https://*.hcaptcha.com' unless values.include?('https://*.hcaptcha.com') || values.include?('https:')
|
|
|
|
policy.send(directive, *values)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2022-01-25 14:56:57 -08:00
|
|
|
def render_captcha
|
2022-01-24 10:06:19 -08:00
|
|
|
return unless captcha_required?
|
|
|
|
|
|
|
|
hcaptcha_tags
|
|
|
|
end
|
|
|
|
end
|