webhook_agent.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. If `payload_path` points to an array,
  19. Events will be created for each element.
  20. MD
  21. end
  22. event_description do
  23. <<-MD
  24. The event payload is based on the value of the `payload_path` option,
  25. which is set to `#{interpolated['payload_path']}`.
  26. MD
  27. end
  28. def default_options
  29. { "secret" => "supersecretstring",
  30. "expected_receive_period_in_days" => 1,
  31. "payload_path" => "some_key"
  32. }
  33. end
  34. def receive_web_request(params, method, format)
  35. secret = params.delete('secret')
  36. return ["Please use POST requests only", 401] unless method == "post"
  37. return ["Not Authorized", 401] unless secret == interpolated['secret']
  38. [payload_for(params)].flatten.each do |payload|
  39. create_event(payload: payload)
  40. end
  41. ['Event Created', 201]
  42. end
  43. def working?
  44. event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
  45. end
  46. def validate_options
  47. unless options['secret'].present?
  48. errors.add(:base, "Must specify a secret for 'Authenticating' requests")
  49. end
  50. end
  51. def payload_for(params)
  52. Utils.value_at(params, interpolated['payload_path']) || {}
  53. end
  54. end
  55. end