【问题标题】:Working example of new recaptcha with Rails?Rails 的新recaptcha 的工作示例?
【发布时间】:2015-03-26 21:13:55
【问题描述】:

有没有人在 Rails 应用程序中提供 Google 新验证码的工作示例?我尝试遵循的每个指南都不清楚或不完整,并且似乎使用了不同的方法。

手卷代码会更好。


正在进行的工作:

config/environments/production.rb:

  #...
  recaptcha_public_key= "[PUBLIC KEY]"
  recaptcha_private_key= "[PRIVATE KEY]"
end

config/environments/development.rb:

  #...
  recaptcha_public_key= "[PUBLIC KEY]"
  recaptcha_private_key= "[PRIVATE KEY]"
end

config/initializers/recaptcha.rb

Recaptcha.configure do |config|
  config.public_key  = Rails.application.secrets.recaptcha_public_key
  config.private_key = Rails.application.secrets.recaptcha_secret_key
  config.api_version = 'v2'
end

【问题讨论】:

  • 你是用宝石还是手卷?我发现了这个,它似乎维护得很好:github.com/ambethia/recaptcha
  • 我本来打算手卷它,因为人们说它应该很简单,但我找不到任何例子。该宝石是否适用于新的recaptcha?我的意思是您只需勾选复选框即可?
  • 是的,但是文档没有更新。请参阅此问题:github.com/ambethia/recaptcha/issues/112 以及相关代码的此拉取请求:github.com/ambethia/recaptcha/pull/115。只需为 v2 设置初始化程序。看起来有几个人在使用它。
  • Ken,我注意到您在我添加答案后添加了帖子的手卷部分。你有什么理由喜欢手卷吗?
  • @SunnyJuneja 过去我在让 gems/plugins 工作时遇到了很多问题。当我可以看到使代码执行其功能的所有内容时,我会更喜欢它。但是我的编程计算机现在无法访问互联网;当我这样做时,我会尝试所有答案,包括宝石,希望其中一个有效。

标签: ruby-on-rails ruby validation ruby-on-rails-4 recaptcha


【解决方案1】:

使用recaptcha gem,我创建了一个使用复选框方法的示例。

此处提供的代码: https://github.com/sunnyrjuneja/recaptcha_example

提交应该很容易遵循。如果您还有其他问题,请告诉我。

此处的示例应用程序: https://recaptcha-checkbox.herokuapp.com/

更新:

这是一种无需secrets.yml 的方法。

将初始化程序更改为如下所示:

Recaptcha.configure do |config|
  config.public_key  = ENV['RECAPTCHA_PUBLIC_KEY']
  config.private_key = ENV['RECAPTCHA_PRIVATE_KEY']
end

在您的开发或生产环境中,将其添加到您的 .bashrc 或 .zshrc。

export RECAPTCHA_PUBLIC_KEY="YOURPUBLICKEY"
export RECAPTCHA_PRIVATE_KEY="YOURPRIVATEKEY"

如果您使用 Heroku 进行部署,请在命令行上执行此操作:

heroku config:set RECAPTCHA_PUBLIC_KEY="YOURPUBLICKEY"
heroku config:set RECAPTCHA_PRIVATE_KEY="YOURPRIVATEKEY"

更新 2:

recaptcha gem 现在使用不同的方法名称来设置键。

Recaptcha.configure do |config| config.site_key = 'YOUR_SITE_KEY_HERE' config.secret_key = 'YOUR_SECRET_KEY_HERE' # Uncomment the following line if you are using a proxy server: # config.proxy = 'http://myproxy.com.au:8080' end

【讨论】:

  • 那么简单的代码<%= recaptcha_tags %> 渲染复选框?
  • 是的。然后在你的控制器中 verify_recaptcha 确保它被正确填写。
  • 您将其添加到初始化程序中。首先,你告诉 Rails 去哪里看 (github.com/whatasunnyday/recaptcha_example/commit/…),然后你可以从 Rails 那里得到它 (github.com/whatasunnyday/recaptcha_example/commit/…)。有很多方法可以管理密钥。最重要的是,如果它在 github 上可供任何人查看,请不要将其放在源代码中。还有其他选项,例如 .dotenv 或 figaro。
  • 我对 yml 不熟悉。我可以手动启动一个名为“secrets.yml”的新文件,还是需要做一些特别的事情来创建该文件?
  • 在 bashrc 中导出 RECAPTCHA_SITE_KEY = '6Lc6BAAAAAAAAChqRbQZcn_yyyyyyyyyyyyyyyyy' & 导出 RECAPTCHA_SECRET_KEY = '6Lc6BAAAAAAAAKN3DRm6VA_xxxxxxxxxxxxxxxxx'
【解决方案2】:

请遵循:

步骤 1. 创建一个 Ruby on Rails 应用程序:-

a)打开终端,导航到您有权创建应用程序的目录并键入: 轨道新回顾

b)创建应用程序后,切换到其文件夹:

$cd recap

c)键入并运行捆绑安装:

$bundle install

第 2 步。创建模型、视图和控制器:-

第 3 步。将 Google Recaptcha 与 Ruby On Rails 集成:-

a) 请登录 Google Recaptcha 网站注册您的域名以获得访问权限。(https://www.google.com/recaptcha/intro/index.html)

b) 请登录并注册您的网站,并附上详细信息 c)注册后google提供

脚本标记将此 sn-p 放在 HTML 模板的结束标记之前。 div 将此 sn-p 放在您想要的位置的末尾 reCAPTCHA 小部件出现。

d)完成上述步骤后,我们可以在网站中看到recaptcha。

f)对于服务器端验证,我们可以使用密钥和将作为参数发送到控制器中的表单提交操作的响应。

g)要检查 Google 是否已验证该用户,请发送带有以下参数的 GET 请求:URL:https://www.google.com/recaptcha/api/siteverify

步骤 4. 更改服务器端验证的应用程序代码。

请查看以下链接了解更多详情,

1) recaptcha-in-rails

2)google-recaptcha-in-rails

在布局中:

<script src='https://www.google.com/recaptcha/api.js'></script>

我的视图app/views/users/_form.html.erb:

&lt;div class="g-recaptcha" data-sitekey="6LdgWwETAAAAAPwAddRqDtNbt9sdfsfsfsdJhggghhKKYTdadsHt54"&gt;&lt;/div&gt;

在初始化器中:

SECRET_KEY = "my_secret_key_here"

在用户控制器中:

 def verify_google_recptcha(secret_key,response)
  status = `curl "https://www.google.com/recaptcha/api/siteverify?secret=#{secret_key}&response=#{response}"`
     logger.info "---------------status ==> #{status}"
     hash = JSON.parse(status)
     hash["success"] == true ? true : false
  end

  def create
    @user = User.new(user_params)
    status = verify_google_recptcha(SECRET_KEY,params["g-recaptcha-response"])
    respond_to do |format|
    if @user.save && status
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: @user }
    else
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end
logger.info "---------------status ==> #{status}" will print like below

出错:

---------------status ==> {
"success": false,
 "error-codes": [
  "missing-input-response"
 ]
}

成功

 ---------------status ==> {
"success": true
}

您可以使用status["error-codes"][0] 并在_form.html.erb 中显示它

heroku查看我的申请

【讨论】:

【解决方案3】:

您应该从RailsCarma's Blog 尝试这个示例。

按照以下步骤操作: 1)获取凭证 2)添加recaptcha标签 3) 要处理验证,请创建一个 recaptcha 类 4) 在 Registrations 控制器中添加 verify_recaptcha 方法

设置 第 1 步:-

将以下内容添加到您的 gem 文件中:

gem “recaptcha”, :require => “recaptcha/rails”

第 2 步:-

登录 developers.google.com 并登录您的 gmail 帐户并搜索“recaptcha”。单击“注册 API 密钥”链接。检查密钥和站点密钥。顾名思义,密钥应保存在更安全的位置,而站点密钥是用于向 Google 进行身份验证的公钥。使用您的 google 帐户注册您的站点名称,以检索稍后将在应用程序中使用的公钥和私钥。

注册完成后,您将获得公钥和私钥。从客户端,公钥被发送到 recaptcha 服务以请求新的验证码。在服务器端应用私钥来验证是否输入了正确的值。

然后注册一个 reCAPTCHA API 密钥并将其添加到您的环境配置文件中:

#put this in development.rb and in production.rb
ENV_RECAPTCHA_PUBLIC_KEY= ‘your-public-key’
ENV_RECAPTCHA_PRIVATE_KEY= ‘your-private-key’

第 3 步:-

Create a file named recaptcha.rb in config/initializers to configure recaptcha parameters.
Recaptcha.configure do |config|
config.public_key = ‘ ENV_RECAPTCHA_PUBLIC_KEY’
config.private_key = ‘ENV_RECAPTCHA_PRIVATE_KEY’
config.proxy = ‘http://www.google.com/recaptcha/api/verify’
end

第 4 步:- 查看

验证码宝石有助于渲染实际的验证码框。就像在您希望验证码出现的位置将以下内容放入您的视图中一样简单:

<%= raw recaptcha_tags %>
If you are using SSL, use this instead:
<%= recaptcha_tags :ssl => true %>, The SSL option ensures we send a https request to the recaptcha service.

第 5 步:- 控制器

Captcha Gem 提供了另一种帮助方法,可以发布到 reCaptcha API 服务器以验证提交是否正确。如果是则该方法返回true,如果不是,它将向模型实例添加一条recaptcha 错误的自定义错误消息。这是您在控制器的创建操作中可能拥有的基本代码:-

在设计控制器 app/controllers/registrations_controller.rb 中,插入以下代码:

require ‘recaptcha.rb’
before_action :verify_recaptcha, only: [:create]
def verify_recaptcha
response = Recaptcha.verify(params)
session[:sign_up] = params[:user].except(:password, :password_confirmation, :remoteip)
if response.code == 200
if response[‘success’]
flash[:notice] = “Recaptcha verification successful.”
else
redirect_to new_user_registration_path(user: params[:user]),
alert: “Recaptcha verification error.”
end
else
redirect_to new_user_registration_path(user: params[:user]),
alert: “HTTP connection error.”
end
end

会话[:sign_up] 被持久化,因为如果验证失败,可以预先填写注册表单。

【讨论】:

    【解决方案4】:

    完整的解决方案,一步一步:

    这里的其他答案不再有效,因为 recaptcha gem 已更新,您可以查看here。这就是我在 Rails 6 应用程序中逐步使用 recaptcha 的方式。

    第 1 步:将 gem 放入您的 Gemfile:

    gem 'recaptcha'

    如果您使用 gems figaro(如我的例子)或 dotenv 来存储 Env 变量,您需要将 recaptcha gem 放在这两个 gem 的声明下方。

    第 2 步:获取验证码 APY 密钥:

    转到属于 Google 的 reCAPTCHA admin console 页面,获取一个用于生产和另一个用于开发的 reCAPTCHA API 密钥(稍后您将了解原因)。暂时将所有这些信息复制到安全的地方。为了在这件事上有一些顺序,因为将来您可能需要其他几个重新验证密钥,您应该为这些重新验证密钥的标签遵循某种独特的符号。例如我的个人网站,所以我称它们为 reiniergarcia_productionreiniergarcia_development

    您需要在此处选择要使用的特定类型的验证码。一种recaptcha 的API 密钥不适用于另一种recaptcha。在我的例子中,我使用了 v2 Checkbox 类型(上面写着:“我不是机器人”)。

    步骤#3:将recaptcha APY密钥存储在rails上:

    在我的例子中,我使用 Figaro 将我的环境变量存储在 rails 上,所以这是我在 config/application.yml 中输入的内容:

    production:
      recaptcha_site_key: 'wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww'
      recaptcha_secret_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    
    development:
      recaptcha_site_key: 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
      recaptcha_secret_key: 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'
    

    第 4 步: 添加 Recaptcha 初始化程序:

    我添加了文件 config/initializers/recaptcha.rb 并在里面放置了:

    Recaptcha.configure do |config|
      # New configuration format:
      config.site_key = Figaro.env.recaptcha_site_key
      config.secret_key = Figaro.env.recaptcha_secret_key
    end
    

    这是新配置。请注意,现在它是 site_key 和 secret_key(不再是 public_key 或 private_key)。 Figaro 将根据环境动态加载正确的密钥。就我而言,我部署到 Heroku,但别担心,因为我很快就会到达那里。

    第 5 步:在表单中放置 recatcha 标签:

    这就是我在我的案例中所做的:

      <%= form_with(model: contact, local: true) do |form| %>
        <%= hidden_field_tag :return_to, return_to %>
    
        <%= form.text_field :name, placeholder: 'Name', autofocus: false %>
        <%= form.email_field :email, placeholder: 'Email', autofocus: false %>
        <%= form.text_field :subject, placeholder: 'Subject', autofocus: false %>
        <%= form.text_area :message, placeholder: 'Message', autofocus: false, disabled: false %>
    
        <div class="row">
          <div class="col-md-6">
            <div style="margin-top: 14px;">
              <%= recaptcha_tags %>
            </div>
          </div>
    
          <div class="col-md-6 submit-button">
            <%= form.submit "SEND", name: "send" %>
          </div>
        </div>
      <% end %>
    

    第 6 步: 为您的 recaptcha 标签设置样式:

    您可能需要在前端(为 recaptcha_tags 帮助程序生成)中设置 recaptcha 标签的位置和/或大小。这就是我在我的案例中所做的:

    我添加了文件 app/assets/stylesheets/recaptcha_tags.scss :

    .g-recaptcha {
      transform: scale(0.6);
      transform-origin: 0 0;
    }
    

    它允许首先减小recaptcha 标签的大小(非常有用,因为recaptcha 标签通常太大)。在您的情况下,如果您需要添加进一步的样式,您应该将它放在那里,而不是与您的其余 css 代码混合。导入该样式文件的方法是在 app/assets/stylesheets/application.scss 处添加以下内容:

    // Imports the recaptcha_tags styling:
    @import "recaptcha_tags";
    

    旁注: 如果您要使用多个布局,则每个布局都应该有一个主 .scss 文件,并且在每个布局上您将只导入该特定布局所必需的内容(仅那些额外的 .scss 严格必要) .

    第 7 步:添加 verify_recaptcha 逻辑:

    您需要在相应控制器的正确操作中添加 verify_recaptcha 逻辑。就我而言,我只想在用户“不是机器人”的情况下保留一个 Contact 对象,所以这就是我在 app/controllers/contacts_controller.rb 中所做的:

      def create
        @contact = contact_service.build_contact(contact_params)
    
        if verify_recaptcha(model: @contact) && @contact.save
          redirect_notice = t('contacts.send.success_notice')
          redirect_to @return_to, notice: redirect_notice
        else
          flash[:alert] = @contact.errors.full_messages.first
          redirect_to @return_to
        end
      end
    

    如果用户没有点击“我不是机器人”,它会在我的页面上显示一个 flash 错误。

    第 8 步: 放置环境。服务器中的变量:

    正如我之前所说,我使用的是 Heroku。所以我只是去了我在 Heroku 中的仪表板,然后我点击了我的项目,稍后在 Settings 选项卡中,然后在一个按钮中显示:“Reveal Config Vars”。然后我将在最后添加以下对(仅限键和值):

      recaptcha_site_key: 'wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww'
      recaptcha_secret_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    

    如你所见,我只添加了生产验证 APY 密钥。

    您可以在终端上执行相同的操作:

    $ heroku config:set recaptcha_site_key=wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
    $ heroku config:set recaptcha_secret_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    

    第 9 步:将所有这些更改推送到 Github:

    $ git push origin master
    

    第 10 步:再次部署到 Heroku:

    $ git push heroku master
    

    就是这样。如果您按照这些步骤操作,您的验证码也应该可以在您的生产网站上完美运行。我希望它有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2014-04-22
      • 1970-01-01
      • 2019-01-01
      • 2010-11-28
      • 2011-07-02
      • 1970-01-01
      相关资源
      最近更新 更多