63 lines
2 KiB
Go
63 lines
2 KiB
Go
package httpapi_test
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"git.az-it.net/az/morz-infoboard/server/backend/internal/httpapi"
|
|
"git.az-it.net/az/morz-infoboard/server/backend/internal/reqcontext"
|
|
"git.az-it.net/az/morz-infoboard/server/backend/internal/store"
|
|
)
|
|
|
|
func userCtx(role string) context.Context {
|
|
return reqcontext.WithUser(context.Background(), &store.User{Role: role})
|
|
}
|
|
|
|
func TestRequireNotRestricted_blocks_restricted(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(userCtx("restricted"))
|
|
rr := httptest.NewRecorder()
|
|
httpapi.RequireNotRestricted(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
t.Fatal("should not be called")
|
|
})).ServeHTTP(rr, req)
|
|
if rr.Code != http.StatusForbidden {
|
|
t.Fatalf("expected 403, got %d", rr.Code)
|
|
}
|
|
}
|
|
|
|
func TestRequireNotRestricted_allows_screen_user(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(userCtx("screen_user"))
|
|
rr := httptest.NewRecorder()
|
|
called := false
|
|
httpapi.RequireNotRestricted(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
called = true
|
|
})).ServeHTTP(rr, req)
|
|
if !called {
|
|
t.Fatal("expected next to be called")
|
|
}
|
|
}
|
|
|
|
func TestRequireNotRestricted_allows_admin(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(userCtx("admin"))
|
|
rr := httptest.NewRecorder()
|
|
called := false
|
|
httpapi.RequireNotRestricted(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
called = true
|
|
})).ServeHTTP(rr, req)
|
|
if !called {
|
|
t.Fatal("expected next to be called")
|
|
}
|
|
}
|
|
|
|
func TestRequireNotRestricted_allows_no_user(t *testing.T) {
|
|
req := httptest.NewRequest(http.MethodPost, "/", nil)
|
|
rr := httptest.NewRecorder()
|
|
called := false
|
|
httpapi.RequireNotRestricted(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
called = true
|
|
})).ServeHTTP(rr, req)
|
|
if !called {
|
|
t.Fatal("no user in context — RequireAuth handles that, this middleware passes through")
|
|
}
|
|
}
|