web_requests_controller.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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_action :verify_authenticity_token
  19. skip_before_action :authenticate_user!
  20. def handle_request
  21. user = User.find_by_id(params[:user_id])
  22. if user
  23. agent = user.agents.find_by_id(params[:agent_id])
  24. if agent
  25. 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)
  26. if content.is_a?(String)
  27. render :text => content, :status => status || 200, :content_type => content_type || 'text/plain'
  28. elsif content.is_a?(Hash)
  29. render :json => content, :status => status || 200
  30. else
  31. head(status || 200)
  32. end
  33. else
  34. render :text => "agent not found", :status => 404
  35. end
  36. else
  37. render :text => "user not found", :status => 404
  38. end
  39. end
  40. # legacy
  41. def update_location
  42. if user = User.find_by_id(params[:user_id])
  43. secret = params[:secret]
  44. user.agents.of_type(Agents::UserLocationAgent).each { |agent|
  45. if agent.options[:secret] == secret
  46. agent.trigger_web_request(params.except(:action, :controller, :user_id, :format), request.method_symbol.to_s, request.format.to_s)
  47. end
  48. }
  49. render :text => "ok"
  50. else
  51. render :text => "user not found", :status => :not_found
  52. end
  53. end
  54. end