Module: XLock

Defined in:
lib/xlock/rack.rb,
lib/xlock/rails.rb,
lib/xlock/verify.rb,
lib/xlock/version.rb

Defined Under Namespace

Modules: Rails Classes: Rack

Constant Summary collapse

API_URL =
ENV.fetch("XLOCK_API_URL", "https://api.x-lock.dev")
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.verify(token:, site_key:, path: "/", api_url: API_URL) ⇒ OpenStruct

Verify an x-lock token against the API.

Parameters:

  • token (String) —

    the x-lock token from the client

  • site_key (String) —

    your site key

  • path (String) (defaults to: "/") —

    the request path being protected

  • api_url (String) (defaults to: API_URL) —

    override the API endpoint

Returns:

  • (OpenStruct) —

    with :blocked (Boolean), :reason (String|nil), :error (String|nil)



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
# File 'lib/xlock/verify.rb', line 18

def self.verify(token:, site_key:, path: "/", api_url: API_URL)
  if token.start_with?("v3.")
    session_id = token.split(".")[1]
    uri = URI("#{api_url}/v3/session/enforce")
    body = { sessionId: session_id, siteKey: site_key, path: path }
  else
    uri = URI("#{api_url}/v1/enforce")
    body = { token: token, siteKey: site_key, path: path }
  end

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.open_timeout = 5
  http.read_timeout = 5

  req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")
  req.body = body.to_json

  res = http.request(req)

  if res.code == "403"
    data = JSON.parse(res.body) rescue {}
    OpenStruct.new(blocked: true, reason: data["reason"], error: nil)
  elsif res.is_a?(Net::HTTPSuccess)
    OpenStruct.new(blocked: false, reason: nil, error: nil)
  else
    OpenStruct.new(blocked: false, reason: nil, error: "Unexpected status #{res.code}")
  end
rescue => e
  OpenStruct.new(blocked: false, reason: nil, error: e.message)
end