1
0

webhook_agent.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. Options:
  13. * `secret` - A token that the host will provide for authentication.
  14. * `expected_receive_period_in_days` - How often you expect to receive
  15. events this way. Used to determine if the agent is working.
  16. * `payload_path` - JSONPath of the attribute in the POST body to be
  17. used as the Event payload. If `payload_path` points to an array,
  18. Events will be created for each element.
  19. MD
  20. end
  21. event_description do
  22. <<-MD
  23. The event payload is based 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" => "some_key"
  31. }
  32. end
  33. def receive_web_request(params, method, format)
  34. secret = params.delete('secret')
  35. return ["Please use POST requests only", 401] unless method == "post"
  36. return ["Not Authorized", 401] unless secret == interpolated['secret']
  37. [payload_for(params)].flatten.each do |payload|
  38. create_event(payload: payload)
  39. end
  40. ['Event Created', 201]
  41. end
  42. def working?
  43. event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
  44. end
  45. def validate_options
  46. unless options['secret'].present?
  47. errors.add(:base, "Must specify a secret for 'Authenticating' requests")
  48. end
  49. end
  50. def payload_for(params)
  51. Utils.value_at(params, interpolated['payload_path']) || {}
  52. end
  53. end
  54. end