middlware: change org when url contains orgid

closes #6948
ref #1613
This commit is contained in:
bergquist
2017-02-17 15:02:14 +01:00
parent 12f1ea71fd
commit 5174d050f2
6 changed files with 120 additions and 1 deletions

View File

@@ -326,6 +326,7 @@ func middlewareScenario(desc string, fn scenarioFunc) {
// mock out gc goroutine
startSessionGC = func() {}
sc.m.Use(Sessioner(&session.Options{}))
sc.m.Use(OrgRedirect())
sc.defaultHandler = func(c *Context) {
sc.context = c

View File

@@ -0,0 +1,41 @@
package middleware
import (
"net/http"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"gopkg.in/macaron.v1"
)
func OrgRedirect() macaron.Handler {
return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
orgId := c.QueryInt64("org-id")
if orgId == 0 {
return
}
ctx, ok := c.Data["ctx"].(*Context)
if !ok || !ctx.IsSignedIn {
return
}
if orgId == ctx.OrgId {
return
}
cmd := models.SetUsingOrgCommand{UserId: ctx.UserId, OrgId: orgId}
if err := bus.Dispatch(&cmd); err != nil {
if ctx.IsApiRequest() {
ctx.JsonApiErr(404, "Not found", nil)
} else {
ctx.Error(404, "Not found")
}
return
}
c.Redirect(c.Req.URL.String(), 302)
}
}

View File

@@ -0,0 +1,60 @@
package middleware
import (
"testing"
"fmt"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
. "github.com/smartystreets/goconvey/convey"
)
func TestOrgRedirectMiddleware(t *testing.T) {
Convey("Can redirect to correct org", t, func() {
middlewareScenario("when setting a correct org for the user", func(sc *scenarioContext) {
sc.fakeReq("GET", "/").handler(func(c *Context) {
c.Session.Set(SESS_KEY_USERID, int64(12))
}).exec()
bus.AddHandler("test", func(query *models.SetUsingOrgCommand) error {
return nil
})
bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
query.Result = &models.SignedInUser{OrgId: 1, UserId: 12}
return nil
})
sc.m.Get("/", sc.defaultHandler)
sc.fakeReq("GET", "/?org-id=3").exec()
Convey("change org and redirect", func() {
So(sc.resp.Code, ShouldEqual, 302)
})
})
middlewareScenario("when setting an invalid org for user", func(sc *scenarioContext) {
sc.fakeReq("GET", "/").handler(func(c *Context) {
c.Session.Set(SESS_KEY_USERID, int64(12))
}).exec()
bus.AddHandler("test", func(query *models.SetUsingOrgCommand) error {
return fmt.Errorf("")
})
bus.AddHandler("test", func(query *models.GetSignedInUserQuery) error {
query.Result = &models.SignedInUser{OrgId: 1, UserId: 12}
return nil
})
sc.m.Get("/", sc.defaultHandler)
sc.fakeReq("GET", "/?org-id=3").exec()
Convey("not allowed to change org", func() {
So(sc.resp.Code, ShouldEqual, 404)
})
})
})
}