1
0

webhook_agent.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. module Agents
  2. class WebhookAgent < Agent
  3. cannot_be_scheduled!
  4. cannot_receive_events!
  5. description do
  6. <<-MD
  7. Use this Agent to create events by receiving webhooks from any source.
  8. In order to create events with this agent, make a POST request to:
  9. ```
  10. https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || '<id>'}/:secret
  11. ``` where `:secret` is specified in your options.
  12. The
  13. Options:
  14. * `secret` - A token that the host will provide for authentication.
  15. * `expected_receive_period_in_days` - How often you expect to receive
  16. events this way. Used to determine if the agent is working.
  17. * `payload_path` - JSONPath of the attribute in the POST body to be
  18. used as the Event payload.
  19. MD
  20. end
  21. event_description do
  22. <<-MD
  23. The event payload is base on the value of the `payload_path` option,
  24. which is set to `#{interpolated['payload_path']}`.
  25. MD
  26. end
  27. def default_options
  28. { "secret" => "supersecretstring",
  29. "expected_receive_period_in_days" => 1,
  30. "payload_path" => "payload"}
  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. create_event(:payload => payload_for(params))
  37. ['Event Created', 201]
  38. end
  39. def working?
  40. event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
  41. end
  42. def validate_options
  43. unless options['secret'].present?
  44. errors.add(:base, "Must specify a secret for 'Authenticating' requests")
  45. end
  46. end
  47. def payload_for(params)
  48. Utils.value_at(params, interpolated['payload_path']) || {}
  49. end
  50. end
  51. end