externalplugin.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package api
  2. import (
  3. "encoding/json"
  4. "github.com/Unknwon/macaron"
  5. "github.com/grafana/grafana/pkg/log"
  6. "github.com/grafana/grafana/pkg/middleware"
  7. "github.com/grafana/grafana/pkg/plugins"
  8. "github.com/grafana/grafana/pkg/util"
  9. "net/http"
  10. "net/http/httputil"
  11. "net/url"
  12. )
  13. func InitExternalPluginRoutes(r *macaron.Macaron) {
  14. /*
  15. // Handle Auth and role requirements
  16. if route.ReqSignedIn {
  17. c.Invoke(middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true}))
  18. }
  19. if route.ReqGrafanaAdmin {
  20. c.Invoke(middleware.Auth(&middleware.AuthOptions{ReqSignedIn: true, ReqGrafanaAdmin: true}))
  21. }
  22. if route.ReqRole != nil {
  23. if *route.ReqRole == m.ROLE_EDITOR {
  24. c.Invoke(middleware.RoleAuth(m.ROLE_EDITOR, m.ROLE_ADMIN))
  25. }
  26. if *route.ReqRole == m.ROLE_ADMIN {
  27. c.Invoke(middleware.RoleAuth(m.ROLE_ADMIN))
  28. }
  29. }
  30. */
  31. for _, plugin := range plugins.ExternalPlugins {
  32. log.Info("adding routes for external plugin")
  33. for _, route := range plugin.Settings.Routes {
  34. log.Info("adding route %s /plugins%s", route.Method, route.Path)
  35. r.Route(util.JoinUrlFragments("/plugins/", route.Path), route.Method, ExternalPlugin(route.Url))
  36. }
  37. }
  38. }
  39. func ExternalPlugin(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 := NewExternalPluginProxy(string(ctx), path, targetUrl)
  50. proxy.Transport = dataProxyTransport
  51. proxy.ServeHTTP(c.RW(), c.Req.Request)
  52. }
  53. }
  54. func NewExternalPluginProxy(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. }