org_redirect.go 1005 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "github.com/grafana/grafana/pkg/bus"
  8. m "github.com/grafana/grafana/pkg/models"
  9. "github.com/grafana/grafana/pkg/setting"
  10. "gopkg.in/macaron.v1"
  11. )
  12. func OrgRedirect() macaron.Handler {
  13. return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
  14. orgIdValue := req.URL.Query().Get("orgId")
  15. orgId, err := strconv.ParseInt(orgIdValue, 10, 32)
  16. if err != nil || orgId == 0 {
  17. return
  18. }
  19. ctx, ok := c.Data["ctx"].(*m.ReqContext)
  20. if !ok || !ctx.IsSignedIn {
  21. return
  22. }
  23. if orgId == ctx.OrgId {
  24. return
  25. }
  26. cmd := m.SetUsingOrgCommand{UserId: ctx.UserId, OrgId: orgId}
  27. if err := bus.Dispatch(&cmd); err != nil {
  28. if ctx.IsApiRequest() {
  29. ctx.JsonApiErr(404, "Not found", nil)
  30. } else {
  31. ctx.Error(404, "Not found")
  32. }
  33. return
  34. }
  35. newURL := setting.ToAbsUrl(fmt.Sprintf("%s?%s", strings.TrimPrefix(c.Req.URL.Path, "/"), c.Req.URL.Query().Encode()))
  36. c.Redirect(newURL, 302)
  37. }
  38. }