Module: Lookout::Rack::Utils::Request

Defined in:
lib/lookout/rack/utils/request.rb

Constant Summary collapse

ILLEGAL_CHARS_REGEX =
/[<>]/
HTTP_CONTENT_ENCODING_KEY =
"HTTP_CONTENT_ENCODING".freeze
CONTENT_ENCODING_GZIPPED =
"gzip".freeze

Instance Method Summary collapse

Instance Method Details

#body_as_jsonObject

Process and parse the request body as JSON

Will halt and create a a 400 status code if there is something wrong with the body



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/lookout/rack/utils/request.rb', line 44

def body_as_json
  body = raw_body

  halt 400, { :error => t('error.body_was_nil') }.to_json if body.nil?
  halt 400, { :error => t('error.body_was_blank') }.to_json if body.blank?

  begin
    return JSON.parse(body)
  rescue JSON::ParserError
    if defined?(Lookout::Rack::Utils::Log)
      Lookout::Rack::Utils::Log.instance.warn "ParserError encountered parsing the request body (#{body})"
    end
    halt 400, "{}"
  end
end

#gunzipped_bodyString

Return the body, which is gunzipped only if the appropriate header is set on the request

Will halt and create a a 400 status code if there is something wrong with the body

Returns:

  • (String)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/lookout/rack/utils/request.rb', line 24

def gunzipped_body
  body = raw_body
  if request.env[HTTP_CONTENT_ENCODING_KEY] != CONTENT_ENCODING_GZIPPED
    return body
  else
    begin
      return gunzip(body)
    rescue Zlib::Error
      if defined?(Lookout::Rack::Utils::Log)
        Lookout::Rack::Utils::Log.instance.warn "Unzipping error when decompressing request body (#{body})"
      end
      halt 400, "{}"
    end
  end
end

#raw_bodyString

Return the raw, unprocessed request body

Returns:

  • (String)


12
13
14
15
16
# File 'lib/lookout/rack/utils/request.rb', line 12

def raw_body
  # Rewind the StringIO object in case somebody else read it first
  request.body.rewind
  return request.body.read
end