RBAC: Redirect to /login when forceLogin is set (#56469) (#56523)

(cherry picked from commit bb479e030a)

Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>
This commit is contained in:
Grot (@grafanabot)
2022-10-07 02:31:19 -04:00
committed by GitHub
co-authored by Emil Tullstedt
parent ba5ee60944
commit 17655071b7
2 changed files with 115 additions and 1 deletions
+50 -1
View File
@@ -83,7 +83,53 @@ func TestMiddleware(t *testing.T) {
}
}
func contextProvider() web.Handler {
func TestMiddleware_forceLogin(t *testing.T) {
tests := []struct {
url string
redirectToLogin bool
}{
{url: "/endpoint?forceLogin=true", redirectToLogin: true},
{url: "/endpoint?forceLogin=false"},
{url: "/endpoint"},
}
for _, tc := range tests {
var endpointCalled bool
server := web.New()
server.UseMiddleware(web.Renderer("../../public/views", "[[", "]]"))
server.Get("/endpoint", func(c *models.ReqContext) {
endpointCalled = true
c.Resp.WriteHeader(http.StatusOK)
})
ac := mock.New().WithPermissions([]accesscontrol.Permission{{Action: "endpoint:read", Scope: "endpoint:1"}})
server.Use(contextProvider(func(c *models.ReqContext) {
c.AllowAnonymous = true
c.SignedInUser.IsAnonymous = true
c.IsSignedIn = false
}))
server.Use(
accesscontrol.Middleware(ac)(nil, accesscontrol.EvalPermission("endpoint:read", "endpoint:1")),
)
request, err := http.NewRequest(http.MethodGet, tc.url, nil)
assert.NoError(t, err)
recorder := httptest.NewRecorder()
server.ServeHTTP(recorder, request)
expectedCode := http.StatusOK
if tc.redirectToLogin {
expectedCode = http.StatusFound
}
assert.Equal(t, expectedCode, recorder.Code)
assert.Equal(t, !tc.redirectToLogin, endpointCalled, "/endpoint should be called?")
}
}
func contextProvider(modifiers ...func(c *models.ReqContext)) web.Handler {
return func(c *web.Context) {
reqCtx := &models.ReqContext{
Context: c,
@@ -92,6 +138,9 @@ func contextProvider() web.Handler {
IsSignedIn: true,
SkipCache: true,
}
for _, modifier := range modifiers {
modifier(reqCtx)
}
c.Req = c.Req.WithContext(ctxkey.Set(c.Req.Context(), reqCtx))
}
}