api_plugin.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httputil"
  6. "net/url"
  7. "github.com/Unknwon/macaron"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/middleware"
  10. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/plugins"
  12. "github.com/grafana/grafana/pkg/util"
  13. )
  14. func InitApiPluginRoutes(r *macaron.Macaron) {
  15. for _, plugin := range plugins.ApiPlugins {
  16. log.Info("Plugin: Adding proxy routes for api plugin")
  17. for _, route := range plugin.Routes {
  18. url := util.JoinUrlFragments("/api/plugin-proxy/", route.Path)
  19. handlers := make([]macaron.Handler, 0)
  20. if route.ReqSignedIn {
  21. handlers = append(handlers, middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true}))
  22. }
  23. if route.ReqGrafanaAdmin {
  24. handlers = append(handlers, middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true}))
  25. }
  26. if route.ReqSignedIn && route.ReqRole != "" {
  27. if route.ReqRole == m.ROLE_ADMIN {
  28. handlers = append(handlers, middleware.RoleAuth(m.ROLE_ADMIN))
  29. } else if route.ReqRole == m.ROLE_EDITOR {
  30. handlers = append(handlers, middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN))
  31. }
  32. }
  33. handlers = append(handlers, ApiPlugin(route.Url))
  34. r.Route(url, route.Method, handlers...)
  35. log.Info("Plugin: Adding route %s", url)
  36. }
  37. }
  38. }
  39. func ApiPlugin(routeUrl string) macaron.Handler {
  40. return func(c *middleware.Context) {
  41. path := c.Params("*")
  42. //Create a HTTP header with the context in it.
  43. ctx, err := json.Marshal(c.SignedInUser)
  44. if err != nil {
  45. c.JsonApiErr(500, "failed to marshal context to json.", err)
  46. return
  47. }
  48. targetUrl, _ := url.Parse(routeUrl)
  49. proxy := NewApiPluginProxy(string(ctx), path, targetUrl)
  50. proxy.Transport = dataProxyTransport
  51. proxy.ServeHTTP(c.RW(), c.Req.Request)
  52. }
  53. }
  54. func NewApiPluginProxy(ctx string, proxyPath string, targetUrl *url.URL) *httputil.ReverseProxy {
  55. director := func(req *http.Request) {
  56. req.URL.Scheme = targetUrl.Scheme
  57. req.URL.Host = targetUrl.Host
  58. req.Host = targetUrl.Host
  59. req.URL.Path = util.JoinUrlFragments(targetUrl.Path, proxyPath)
  60. // clear cookie headers
  61. req.Header.Del("Cookie")
  62. req.Header.Del("Set-Cookie")
  63. req.Header.Add("Grafana-Context", ctx)
  64. }
  65. return &httputil.ReverseProxy{Director: director}
  66. }