webhooks_controller.rb 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # This controller is designed to allow your Agents to receive cross-site Webhooks (posts). When POSTed, your Agent will
  2. # have #receive_webhook called on itself with the POST params.
  3. #
  4. # Make POSTs to the following URL:
  5. # http://yourserver.com/users/:user_id/webhooks/:agent_id/:secret
  6. # where :user_id is your User's id, :agent_id is an Agent's id, and :secret is a token that should be
  7. # user-specifiable in your Agent. It is highly recommended that you verify this token whenever #receive_webhook
  8. # is called. For example, one of your Agent's options could be :secret and you could compare this value
  9. # to params[:secret] whenever #receive_webhook is called on your Agent, rejecting invalid requests.
  10. #
  11. # Your Agent's #receive_webhook method should return an Array of [json_or_string_response, status_code]. For example:
  12. # [{status: "success"}, 200]
  13. # or
  14. # ["not found", 404]
  15. class WebhooksController < ApplicationController
  16. skip_before_filter :authenticate_user!
  17. def create
  18. user = User.find_by_id(params[:user_id])
  19. if user
  20. agent = user.agents.find_by_id(params[:agent_id])
  21. if agent
  22. response, status = agent.trigger_webhook(params.except(:action, :controller, :agent_id, :user_id))
  23. if response.is_a?(String)
  24. render :text => response, :status => status || 200
  25. elsif response.is_a?(Hash)
  26. render :json => response, :status => status || 200
  27. else
  28. head :ok
  29. end
  30. else
  31. render :text => "agent not found", :status => :not_found
  32. end
  33. else
  34. render :text => "user not found", :status => :not_found
  35. end
  36. end
  37. end