class Yunpian::Captcha::AuthService

Constants

PARAMS

Attributes

authenticate[R]
config[R]
token[R]

Public Class Methods

new(token, authenticate, config = Yunpian::Captcha.config) click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 9
def initialize(token, authenticate, config = Yunpian::Captcha.config)
  @config, @token, @authenticate = config, token, authenticate
end

Public Instance Methods

call() click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 13
def call
  log :debug, 'verifying'
  signed_params = sign(build_params)
  valid?(signed_params)
end

Private Instance Methods

build_params() click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 44
def build_params
  {
    captchaId: config.app_id,
    token: token,
    authenticate: authenticate,
    secretId: config.secret_id,
    version: '1.0',
    timestamp: (Time.now.to_f * 1000).to_i,
    nonce: rand(1..99_999)
  }
end
log(type, message) click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 56
def log(type, message)
  return unless logger

  logger.send type,
              "[YunPian Captcha][token=#{token}, " \
              "authenticate=#{authenticate}] " \
              "#{message}"
end
logger() click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 65
def logger
  @logger ||= config.logger
end
record_exception!(result) click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 69
def record_exception!(result)
  config.exception_recorder&.call(result)
end
sign(params) click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 32
def sign(params)
  params.tap do |p|
    p[:signature] = signature(params)
  end
end
signature(params) click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 38
def signature(params)
  str = params.sort.inject("") { |ret, kv| ret << kv.join }
  str << config.secret_key
  Digest::MD5.hexdigest(str)
end
valid?(signed_params) click to toggle source
# File lib/yunpian/captcha/auth_service.rb, line 21
def valid?(signed_params)
  log :debug, "signed params is #{signed_params}"
  resp = Net::HTTP.post_form(API_URI, signed_params)
  log :debug, "API response => #{resp.body}"
  result = JSON.parse(resp.body) rescue nil
  return true if result && result['code'].zero?

  record_exception!(result)
  false
end