Integration guide for Ruby on Rails applications.
Full Example
A complete working example is available on GitHub: Captchacat-Integrations/Ruby-on-Rails
Configuration#
Set your Captchacat credentials:
CAPTCHACAT_SITE_KEY = "" # Your site keyCAPTCHACAT_API_KEY = "" # Your API keyValidator#
Create a service class to validate the CAPTCHA token:
require "net/http"
require "json"
class CaptchacatValidator
CAPTCHACAT_API_KEY = "" # Your API key
def self.validate(token)
return { valid: false, message: "Token is missing" } if token.nil? || token.empty?
uri = URI.parse("https://challenge.captchacat.com/validate_token")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path)
request["Content-Type"] = "application/json"
request.body = { api_key: CAPTCHACAT_API_KEY, token: token }.to_json
response = http.request(request)
if response.code.to_i >= 200 && response.code.to_i < 300
{ valid: true }
else
{ valid: false, message: "Server error: #{response.code}" }
end
rescue StandardError => e
{ valid: false, message: e.message }
end
endView#
Add the widget to your form:
<script src="https://challenge.captchacat.com/ray/widget.js"></script>
<%= form_tag login_path, method: :post do %>
<div class="form-field">
<%= label_tag :username, "Username" %>
<%= text_field_tag :username, nil, placeholder: "Enter your username", required: true %>
</div>
<div class="form-field">
<%= label_tag :password, "Password" %>
<%= password_field_tag :password, nil, placeholder: "Enter your password", required: true %>
</div>
<div class="captcha-widget" data-sitekey="<%= @site_key %>"></div>
<%= submit_tag "Sign In" %>
<% end %>Controller#
class SessionsController < ApplicationController
CAPTCHACAT_SITE_KEY = "" # Your site key
def new
@site_key = CAPTCHACAT_SITE_KEY
end
def create
token = params["captchacat-token"]
result = CaptchacatValidator.validate(token)
if result[:valid]
# Token valid - process the form
flash[:success] = "Login successful!"
redirect_to root_path
else
flash[:error] = "CAPTCHA verification failed"
@site_key = CAPTCHACAT_SITE_KEY
render :new
end
end
endRoutes#
Rails.application.routes.draw do
get "/login", to: "sessions#new"
post "/login", to: "sessions#create"
end