webhook_agent.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. module Agents
  2. class WebhookAgent < Agent
  3. cannot_be_scheduled!
  4. cannot_receive_events!
  5. description do <<-MD
  6. The Webhook Agent will create events by receiving webhooks from any source. In order to create events with this agent, make a POST request to:
  7. ```
  8. https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || ':id'}/#{options['secret'] || ':secret'}
  9. ```
  10. #{'The placeholder symbols above will be replaced by their values once the agent is saved.' unless id}
  11. Options:
  12. * `secret` - A token that the host will provide for authentication.
  13. * `expected_receive_period_in_days` - How often you expect to receive
  14. events this way. Used to determine if the agent is working.
  15. * `payload_path` - JSONPath of the attribute in the POST body to be
  16. used as the Event payload. If `payload_path` points to an array,
  17. Events will be created for each element.
  18. MD
  19. end
  20. event_description do
  21. <<-MD
  22. The event payload is based on the value of the `payload_path` option,
  23. which is set to `#{interpolated['payload_path']}`.
  24. MD
  25. end
  26. def default_options
  27. { "secret" => "supersecretstring",
  28. "expected_receive_period_in_days" => 1,
  29. "payload_path" => "some_key"
  30. }
  31. end
  32. def receive_web_request(params, method, format)
  33. secret = params.delete('secret')
  34. return ["Please use POST requests only", 401] unless method == "post"
  35. return ["Not Authorized", 401] unless secret == interpolated['secret']
  36. [payload_for(params)].flatten.each do |payload|
  37. create_event(payload: payload)
  38. end
  39. ['Event Created', 201]
  40. end
  41. def working?
  42. event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
  43. end
  44. def validate_options
  45. unless options['secret'].present?
  46. errors.add(:base, "Must specify a secret for 'Authenticating' requests")
  47. end
  48. end
  49. def payload_for(params)
  50. Utils.value_at(params, interpolated['payload_path']) || {}
  51. end
  52. end
  53. end