Skip to content

Instantly share code, notes, and snippets.

@hendricius
Created August 9, 2022 16:24
Show Gist options
  • Save hendricius/616694e449ed6a7777d0a21675dfe636 to your computer and use it in GitHub Desktop.
Save hendricius/616694e449ed6a7777d0a21675dfe636 to your computer and use it in GitHub Desktop.
Friendlycapture Ruby service class
class FriendlyCaptcha
class Error < StandardError; end
def initialize(token)
@token = token
end
# FriendlyCaptcha.valid?("my token that was passed from frontend")
def self.valid?(token)
new(token).valid?
end
def valid?
handle_api_response(verify_token_request(@token))
rescue FriendlyCaptcha::Error
# In case of a HTTP error or json error we gracefully
# return true so that the user is not annoyed.
true
end
private
def handle_api_response(response)
# graceful API error handling. It will always return 200
return true unless response.status == 200
res = JSON.parse(response.body, symbolize_names: true)
res[:success]
rescue JSON::ParserError, Faraday::Error
raise FriendlyCaptcha::Error
end
def http_service
Faraday.new(
url: 'https://api.friendlycaptcha.com',
headers: {'Content-Type' => 'application/json'}
)
end
def verify_token_request(tok)
body = {
solution: tok,
# get these values from your friendlycapture setup
secret: Rails.application.config.x.friendly_captcha[:api_key],
sitekey: Rails.application.config.x.friendly_captcha[:key],
}
http_service.post('/api/v1/siteverify') do |req|
req.body = body.to_json
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment