2026-07-14 17:12:39 +08:00

53 lines
1.5 KiB
Go

package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"hyapp-admin-server/internal/model"
"hyapp-admin-server/internal/repository"
"github.com/gin-gonic/gin"
)
type fakeAppAccessStore struct {
access repository.AppAccess
}
func (store fakeAppAccessStore) AppAccessForUser(uint) (repository.AppAccess, error) {
return store.access, nil
}
func TestRequireAppScopeAllowsOnlySelectedApp(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(ContextUserID, uint(7))
})
router.GET("/app", RequireAppScope(fakeAppAccessStore{access: repository.AppAccess{
Mode: model.UserAppScopeModeSelected,
AppCodes: []string{"lalu"},
}}), func(c *gin.Context) { c.Status(http.StatusNoContent) })
allowed := httptest.NewRequest(http.MethodGet, "/app", nil)
allowed.Header.Set("X-App-Code", "LALU")
allowedResponse := httptest.NewRecorder()
router.ServeHTTP(allowedResponse, allowed)
if allowedResponse.Code != http.StatusNoContent {
t.Fatalf("allowed status = %d body=%s", allowedResponse.Code, allowedResponse.Body.String())
}
for _, header := range []string{"", "huwaa"} {
request := httptest.NewRequest(http.MethodGet, "/app", nil)
if header != "" {
request.Header.Set("X-App-Code", header)
}
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusForbidden {
t.Fatalf("header %q status = %d body=%s", header, response.Code, response.Body.String())
}
}
}