feat(tenant): 按租户隔离用户身份与后台权限
This commit is contained in:
@@ -7,10 +7,19 @@ import (
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/modules/auth"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func useRequestTenant(tenantID uint64) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := tenancy.WithScope(c.Request.Context(), tenancy.Scope{TenantID: tenantID})
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAuthRejectsQueryToken(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
manager := auth.NewJWTManager("test-jwt-secret-for-query-token-rejection")
|
||||
@@ -63,3 +72,42 @@ func TestAuthRejectsRevokedUserToken(t *testing.T) {
|
||||
t.Fatalf("响应状态 = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserAndAdminTokensRejectCrossTenantRequests(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
manager := auth.NewJWTManager("cross-tenant-auth-test-secret")
|
||||
userPair, err := manager.GenerateTenantPairWithVersion(1, "13800000000", "user", 1, 101)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adminPair, err := manager.GenerateTenantPairWithVersion(2, "admin", "admin", 1, 101)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
userEngine := gin.New()
|
||||
userEngine.Use(useRequestTenant(202))
|
||||
userEngine.GET("/protected", Auth(manager, nil), func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
userRequest := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||
userRequest.Header.Set("Authorization", "Bearer "+userPair.AccessToken)
|
||||
userResponse := httptest.NewRecorder()
|
||||
userEngine.ServeHTTP(userResponse, userRequest)
|
||||
if userResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("cross-tenant user token status = %d, want 401", userResponse.Code)
|
||||
}
|
||||
|
||||
adminEngine := gin.New()
|
||||
adminEngine.Use(useRequestTenant(202))
|
||||
adminEngine.GET("/protected", AdminAuth(manager, nil), func(c *gin.Context) {
|
||||
c.Status(http.StatusNoContent)
|
||||
})
|
||||
adminRequest := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||
adminRequest.Header.Set("Authorization", "Bearer "+adminPair.AccessToken)
|
||||
adminResponse := httptest.NewRecorder()
|
||||
adminEngine.ServeHTTP(adminResponse, adminRequest)
|
||||
if adminResponse.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("cross-tenant admin token status = %d, want 401", adminResponse.Code)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user