Top Level Namespace

Constant Summary collapse

VALID_IP_ADDRESS =

Don’t you love regular expressions? Matches only 0-255 octets. Recognizes “*” as an octet wildcard.

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|\*)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|\*)$/
RESTFUL_API_HANDLER =
lambda do |env|
  json = env["rack.input"].read

  # Return "Bad Request" HTTP error if the client forgot
  return [400, {}, "You must POST a valid JSON object!"] if json.blank?

  json = JSON.parse json

  nesting = COMPONENTS.send(:'ahn-restful-rpc')["path_nesting"]
  path = env["PATH_INFO"]

  return [404, {}, "This resource does not respond to #{path.inspect}"] unless path[0...nesting.size] == nesting

  path = path[nesting.size..-1]

  return [404, {"Content-Type" => "application/json"}, "You cannot nest method names!"] if path.include?("/")

  rpc_object = Adhearsion::Components.component_manager.extend_object_with(Object.new, :rpc)

  # TODO: set the content-type and other HTTP headers
  response_object = rpc_object.send(path, *json)
  [200, {"Content-Type" => "application/json"}, Array(response_object.to_json)]

end

Instance Method Summary collapse

Instance Method Details

#ip_allowed?(ip) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


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
# File 'lib/ahn-restful-rpc.rb', line 11

def ip_allowed?(ip)
  raise ArgumentError, "#{ip.inspect} is not a valid IP address!" unless ip.kind_of?(String) && ip =~ VALID_IP_ADDRESS

  octets = ip.split "."

  case COMPONENTS.send(:'ahn-restful-rpc')["access"]
    when "everyone"
      true
    when "whitelist"
      whitelist = COMPONENTS.send(:'ahn-restful-rpc')["whitelist"]
      !! whitelist.find do |pattern|
        pattern_octets = pattern.split "."
        # Traverse both arrays in parallel
        octets.zip(pattern_octets).map do |octet, octet_pattern|
          octet_pattern == "*" ? true : (octet == octet_pattern)
        end == [true, true, true, true]
      end
    when "blacklist"
      blacklist = COMPONENTS.send(:'ahn-restful-rpc')["blacklist"]
      ! blacklist.find do |pattern|
        pattern_octets = pattern.split "."
        # Traverse both arrays in parallel
        octets.zip(pattern_octets).map do |octet, octet_pattern|
          octet_pattern == "*" ? true : (octet == octet_pattern)
        end == [true, true, true, true]
      end
    else
      raise Adhearsion::Components::ConfigurationError, 'Unrecognized "access" configuration value!'
  end
end