web_requests_controller.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # This controller is designed to allow your Agents to receive cross-site Webhooks (POSTs), or to output data streams.
  2. # When a POST or GET is received, your Agent will have #receive_web_request called on itself with the incoming params,
  3. # method, and requested content-type.
  4. #
  5. # Requests are routed as follows:
  6. # http://yourserver.com/users/:user_id/web_requests/:agent_id/:secret
  7. # where :user_id is a User's id, :agent_id is an Agent's id, and :secret is a token that should be user-specifiable in
  8. # an Agent that implements #receive_web_request. It is highly recommended that every Agent verify this token whenever
  9. # #receive_web_request is called. For example, one of your Agent's options could be :secret and you could compare this
  10. # value to params[:secret] whenever #receive_web_request is called on your Agent, rejecting invalid requests.
  11. #
  12. # Your Agent's #receive_web_request method should return an Array of json_or_string_response, status_code, and
  13. # optional mime type. For example:
  14. # [{status: "success"}, 200]
  15. # or
  16. # ["not found", 404, 'text/plain']
  17. class WebRequestsController < ApplicationController
  18. skip_before_filter :authenticate_user!
  19. def handle_request
  20. user = User.find_by_id(params[:user_id])
  21. if user
  22. agent = user.agents.find_by_id(params[:agent_id])
  23. if agent
  24. content, status, content_type = agent.trigger_web_request(params.except(:action, :controller, :agent_id, :user_id, :format), request.method_symbol.to_s, request.format.to_s)
  25. if content.is_a?(String)
  26. render :text => content, :status => status || 200, :content_type => content_type || 'text/plain'
  27. elsif content.is_a?(Hash)
  28. render :json => content, :status => status || 200
  29. else
  30. head(status || 200)
  31. end
  32. else
  33. render :text => "agent not found", :status => 404
  34. end
  35. else
  36. render :text => "user not found", :status => 404
  37. end
  38. end
  39. # legacy
  40. def update_location
  41. if user = User.find_by_id(params[:user_id])
  42. secret = params[:secret]
  43. user.agents.of_type(Agents::UserLocationAgent).each { |agent|
  44. if agent.options[:secret] == secret
  45. agent.trigger_web_request(params.except(:action, :controller, :user_id, :format), request.method_symbol.to_s, request.format.to_s)
  46. end
  47. }
  48. render :text => "ok"
  49. else
  50. render :text => "user not found", :status => :not_found
  51. end
  52. end
  53. end