Recaptcha gem error“未指定站点密钥。”

时间:2018-03-10 23:00:21

标签: ruby-on-rails ruby-on-rails-5 recaptcha invisible-recaptcha

我正在尝试在我的rails 5应用程序中设置Recaptcha,因为它在文档中有描述,但它失败了。

我使用这个宝石:recaptcha (4.6.6)ruby 2.5.0rails 5.1.4

以视图形式:

<%= flash[:recaptcha_error] %>
<%= recaptcha_tags %>

在设计注册控制器:

  prepend_before_action :check_captcha, only: :create

  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
      respond_with_navigational(resource) { redirect_to new_user_registration_path }
    end 
  end

在我的初始化者/ recaptcha.rb

Recaptcha.configure do |config|
  config.site_key   = Rails.application.config_for(:recaptcha)['site_key']
  config.secret_key = Rails.application.config_for(:recaptcha)['secret_key']
end

在我的recaptcha.yml中:

default: &default
  site_key: <%= ENV["RECAPTCHA_SITE_KEY"] %>
  secret_key: <%= ENV["RECAPTCHA_SECRET_KEY"] %>

development:
  <<: *default

test:
  <<: *default

staging:
  <<: *default

production:
  <<: *default

在/ etc / environments中:

# RECAPTCHA
RECAPTCHA_SITE_KEY=6Lfg3ksUAAAAABOD_OXCtPO60*******
RECAPTCHA_SECRET_KEY=6Lfg3ksUAAAAAOmFGdAxdo8*******

问题

将ENV变量添加到/etc/environments后,我使用以下命令导出它:

for line in $( cat /etc/environment ) ; do export $line ; done

然后我检查Recaptcha模块配置是否正确:

/home/deploy/apps/app_name/current$ bundle exec rails c
Loading staging environment (Rails 5.1.4) 
2.5.0 :001 > Recaptcha::Configuration.new
 => #<Recaptcha::Configuration:0x0000000006601908 @skip_verify_env=["test", "cucumber"], @handle_timeouts_gracefully=true, @secret_key="6Lfg3ksUAAAAAOmFGdAxdo8H*************", @site_key="6Lfg3ksUAAAAABOD_OXCtPO*************"> 
2.5.0 :002 > Recaptcha::Configuration.new.site_key!
 => "6Lfg3ksUAAAAABOD_OXCtPO*************" 

另外,当我运行printenv命令时,我看到这些ENV变量(所以它真的被加载了)

之后,我重新启动了rails并出现了错误

  

未指定网站密钥。

/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/configuration.rb:47:in `site_key!'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/client_helper.rb:79:in `recaptcha_components'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/recaptcha-4.6.6/lib/recaptcha/client_helper.rb:15:in `recaptcha_tags'
/home/deploy/apps/app_name/releases/20180310222304/app/views/users/registrations/new.html.erb:27:in `block in _app_views_users_registrations_new_html_erb___216558772140569572_69973306795360'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:39:in `block in capture'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:203:in `with_output_buffer'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/capture_helper.rb:39:in `capture'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/helpers/form_helper.rb:450:in `form_for'
/home/deploy/apps/app_name/releases/20180310222304/app/views/users/registrations/new.html.erb:21:in `_app_views_users_registrations_new_html_erb___216558772140569572_69973306795360'
/home/deploy/apps/app_name/shared/bundle/ruby/2.5.0/gems/actionview-5.1.4/lib/action_view/template.rb:157:in `block in render'

4 个答案:

答案 0 :(得分:0)

我仍然不知道“No site key specified”错误的原因是什么。

我真的不喜欢gem 'recapthca'直接使用ENV变量,

我也花了太多时间进行调查。

所以,我决定不使用这个gem并编写我自己的代码。

我在我的应用程序中只使用Invisible Recaptcha

配置文件(加载机密密钥和网站密钥)

# /config/recaptcha.yml
default: &default
  site_key: <%= ENV["RECAPTCHA_SITE_KEY"] %>
  secret_key: <%= ENV["RECAPTCHA_SECRET_KEY"] %>

development:
  <<: *default

test:
  <<: *default

staging:
  <<: *default

production:
  <<: *default

应用程序助手(带Recaptcha助手的按钮)

# /app/helpers/application_helper.rb
module ApplicationHelper
  def submit_with_recaptcha(text, custom_options)
    unless custom_options[:data].has_key?(:form_id) 
      raise "Data Form Id option not found ('{data: {form_id: 'id_without_dash'}')."
    end

    options = {
      type: 'button',
      data: {
        form_id: custom_options[:data][:form_id],
        sitekey: recaptcha_site_key,
        callback: "submit#{custom_options[:data][:form_id].camelize}#{Time.current.to_i}"
      },
      class: (custom_options[:class].split(' ') + ['g-recaptcha']).uniq.join(' ')
    }

    script_code = <<-SCRIPT
      function #{options[:data][:callback]}() {
        document.getElementById('#{options[:data][:form_id]}').submit();
      }
    SCRIPT

    javascript_tag(script_code) + content_tag(:div, class: 'recaptcha_wrapper'){ submit_tag(text, options) }
  end

  private

  def recaptcha_site_key
    Rails.application.config_for(:recaptcha)['site_key']
  end
end

验证服务(因为它使用外部API)

# app/services/google_recaptcha/verification.rb
module GoogleRecaptcha
  # https://developers.google.com/recaptcha/docs/verify
  class Verification
    # response - params['g-recaptcha-response'])
    def self.successful?(recaptcha_params, remoteip)
      verify_url = URI.parse('https://www.google.com/recaptcha/api/siteverify')
      verify_request = Net::HTTP::Post.new(verify_url.path)

      verify_request.set_form_data(
        response: recaptcha_params,
        secret: secret_key,
        remoteip: remoteip
      )

      connection = Net::HTTP.new(verify_url.host, verify_url.port)
      connection.use_ssl = true

      Rails.logger.info '[RECAPTCHA] Sending verification request.'

      verify_response = connection.start { |http| http.request(verify_request) }
      response_data = JSON.parse(verify_response.body)

      Rails.logger.info "[RECAPTCHA] Verification response is#{' not' unless response_data['success']} successful."

      response_data['success']
    end

    private

    def self.secret_key
      Rails.application.config_for(:recaptcha)['secret_key']
    end
  end
end

控制器关注(before_action中的Recaptcha验证)

# app/controllers/concerns/recaptchable.rb
module Recaptchable
  extend ActiveSupport::Concern

  included do
    before_action :verify_recaptcha, only: [:create]
  end

  private

  def verify_recaptcha
    unless GoogleRecaptcha::Verification.successful?(recaptcha_params['g-recaptcha-response'], request.remote_ip)
      render :new
      return
    end
  end

  def recaptcha_params
    params.permit(:'g-recaptcha-response')
  end
end

<强>用法

添加您对控制器的关注:

class MyController < ShopController
  include Recaptchable
end

www.google.com/recaptcha/api.js javascript添加到您的网页

submit_with_recaptcha帮助器添加到表单

<%= form_for @delivery, url: users_delivery_path, method: 'post' do |f| %>
  <%= submit_with_recaptcha t('order.deliver.to_confirmation'), data: {form_id: 'new_delivery'}, class: 'btn-round' %>

<% end %>
<%= javascript_include_tag "https://www.google.com/recaptcha/api.js?hl=#{I18n.locale}", 'data-turbolinks-track': 'reload' %>

就是这样。

答案 1 :(得分:0)

注意:我在这里发布此答案,以供可能发现此问题的人参考。这是我解决问题的方法。

我将local_env.yml用于环境变量。我刚开始使用gem,然后将RECAPTCHA_SITE_KEY和RECAPTCHA_SECRET_KEY添加到local_env.yml。我遇到了同样的错误。

花了一点时间才知道宝石直接使用了变量。我最终将以下语句放在~/.bashrc中,类似于文档中所说的内容,但在值两边没有引号。

export RECAPTCHA_SITE_KEY=6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy
export RECAPTCHA_SECRET_KEY=6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx

我在Heroku上托管我的应用程序。我执行了以下终端命令以在Heroku中设置环境变量。

heroku config:set RECAPTCHA_SITE_KEY=‘6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy’
heroku config:set RECAPTCHA_SECRET_KEY=‘6LcGuI4U6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxxAAAAGAWMYRKFGfHUCSD0SPrMX2lfyl9’

答案 2 :(得分:0)

您在使用nginx吗? Nginx删除了ENV变量(TZ除外),并且recapcha宝石似乎对此特别敏感。根据经验,当使用dotenv宝石时,其他ENV变量正常工作时,将忽略重新配置ENV变量。

您可以通过在enginx.conf的顶部添加env变量来解决此问题。

env RECAPTCHA_SITE_KEY=value1;
env RECAPTCHA_SECRET_KEY=value2;

Here's nginx's documentation on the matter.

答案 3 :(得分:0)

如果有人正在寻找用于设置Recaptcha密钥的Rails 5.2解决方案,我会在此处发布。该解决方案利用了新的config / master.key和config / credentials.yml.enc加密文件。

  1. 通过在本地终端中编辑文件,将Recaptcha密钥添加到certificate.yml.enc文件中:

    EDITOR="vim" rails credentials:edit

  2. 将密钥添加到凭据文件后(请参见下面的示例),保存并退出文件。退出后,然后将自动对certificate.yml.enc文件进行加密。 master.key是应用程序解密所必需的。加密之前:

    recaptcha_site_key: 6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy recaptcha_secret_key: 6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxx


3.在Rails应用程序中创建一个名为config / recaptcha.rb的文件,并向其中添加以下代码:
     Recaptcha.configure do |config| config.site_key = Rails.application.credentials.dig(:recaptcha_site_key) config.secret_key = Rails.application.credentials.dig(:recaptcha_secret_key) end

此解决方案在本地和生产环境中的Ubuntu / nginx上均可使用。您不需要gem或环境变量即可工作。如果master.key解密失败,则可能需要删除certificate.yml.enc文件,甚至可能要删除master.key文件,然后在本地重复此过程(EDITOR =“ vim” rails certificate:edit等)。在将新的master.key复制到生产并重新部署之前。