org_redirect.go 968 B

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