File: reply.rb

package info (click to toggle)
ruby-recaptcha 5.21.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 208 kB
  • sloc: ruby: 662; makefile: 3
file content (118 lines) | stat: -rw-r--r-- 2,284 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# frozen_string_literal: true

module Recaptcha
  class Reply
    def initialize(raw_reply, enterprise:)
      @raw_reply = raw_reply
      @enterprise = enterprise
    end

    def [](key)
      @raw_reply[key.to_s]
    end

    def success?(options = {})
      success.to_s == 'true' &&
        hostname_valid?(options[:hostname]) &&
        action_valid?(options[:action]) &&
        score_above_threshold?(options[:minimum_score]) &&
        score_below_threshold?(options[:maximum_score])
    end

    def token_properties
      @raw_reply['tokenProperties'] if enterprise?
    end

    def success
      if enterprise?
        token_properties&.dig('valid')
      else
        @raw_reply['success']
      end
    end

    def hostname
      if enterprise?
        token_properties&.dig('hostname')
      else
        @raw_reply['hostname']
      end
    end

    def action
      if enterprise?
        token_properties&.dig('action')
      else
        @raw_reply['action']
      end
    end

    def score
      if enterprise?
        @raw_reply.dig('riskAnalysis', 'score')
      else
        @raw_reply['score'] unless enterprise?
      end
    end

    def error_codes
      if enterprise?
        []
      else
        @raw_reply['error-codes'] || []
      end
    end

    def challenge_ts
      return @raw_reply['challenge_ts'] unless enterprise?

      token_properties&.dig('createTime')
    end

    def hostname_valid?(validation)
      validation ||= Recaptcha.configuration.hostname

      case validation
      when nil, FalseClass
        true
      when String
        validation == hostname
      else
        validation.call(hostname)
      end
    end

    def action_valid?(expected_action)
      case expected_action
      when nil, FalseClass
        true
      else
        action == expected_action.to_s
      end
    end

    def score_above_threshold?(minimum_score)
      !minimum_score || (score && score >= minimum_score)
    end

    def score_below_threshold?(maximum_score)
      !maximum_score || (score && score <= maximum_score)
    end

    def enterprise?
      @enterprise
    end

    def to_h
      @raw_reply
    end

    def to_s
      @raw_reply.to_s
    end

    def to_json(*args)
      @raw_reply.to_json(*args)
    end
  end
end