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

This commit is contained in:
Emil Tullstedt
2022-10-07 08:18:56 +02:00
committed by GitHub
parent b622a87aee
commit bb479e030a
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))
}
}