fix(distribution): 修复删除测试并新增分站只读二维码池
This commit is contained in:
@@ -702,11 +702,12 @@ func (r *Repository) DeleteSite(ctx context.Context, adminID, siteID uint64) err
|
||||
|
||||
// 4. 检查钱包账户余额
|
||||
var walletAccounts []model.WalletAccount
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID).Find(&walletAccounts).Error; err == nil {
|
||||
for _, wa := range walletAccounts {
|
||||
if wa.AvailableBalanceCent > 0 || wa.FrozenBalanceCent > 0 {
|
||||
return fmt.Errorf("分销站点【%s】钱包尚有未结算/未提现余额,无法删除", site.SiteName)
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Where("distribution_site_id = ?", siteID).Find(&walletAccounts).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, wa := range walletAccounts {
|
||||
if wa.AvailableBalanceCent != 0 || wa.FrozenBalanceCent != 0 {
|
||||
return fmt.Errorf("分销站点【%s】钱包尚有未结算/未提现余额,无法删除", site.SiteName)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -726,18 +727,27 @@ func (r *Repository) DeleteSite(ctx context.Context, adminID, siteID uint64) err
|
||||
// 若管理员用户仅绑定此分销站点且非系统超管,清理其账号与角色,便于用户名复用
|
||||
for _, m := range members {
|
||||
var otherMemberCount int64
|
||||
_ = tx.Model(&model.DistributionSiteMember{}).Where("admin_user_id = ?", m.AdminUserID).Count(&otherMemberCount).Error
|
||||
if err := tx.Model(&model.DistributionSiteMember{}).Where("admin_user_id = ?", m.AdminUserID).Count(&otherMemberCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if otherMemberCount == 0 {
|
||||
var adminUser model.AdminUser
|
||||
if err := tx.First(&adminUser, m.AdminUserID).Error; err == nil {
|
||||
var superRoleCount int64
|
||||
_ = tx.Table("admin_user_roles").
|
||||
Joins("JOIN roles ON roles.id = admin_user_roles.role_id").
|
||||
Where("admin_user_roles.admin_user_id = ? AND roles.code IN ('super_admin', 'admin')", m.AdminUserID).
|
||||
Count(&superRoleCount).Error
|
||||
if superRoleCount == 0 {
|
||||
_ = tx.Table("admin_user_roles").Where("admin_user_id = ?", m.AdminUserID).Delete(nil).Error
|
||||
_ = tx.Delete(&adminUser).Error
|
||||
if err := tx.First(&adminUser, m.AdminUserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
var superRoleCount int64
|
||||
if err := tx.Table("admin_user_roles").
|
||||
Joins("JOIN roles ON roles.id = admin_user_roles.role_id").
|
||||
Where("admin_user_roles.admin_user_id = ? AND roles.code IN ('super_admin', 'admin')", m.AdminUserID).
|
||||
Count(&superRoleCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if superRoleCount == 0 {
|
||||
if err := tx.Table("admin_user_roles").Where("admin_user_id = ?", m.AdminUserID).Delete(nil).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Delete(&adminUser).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -758,9 +768,10 @@ func (r *Repository) DeleteSite(ctx context.Context, adminID, siteID uint64) err
|
||||
return err
|
||||
}
|
||||
|
||||
// 清理分销钱包与钱包账户
|
||||
_ = tx.Table("distribution_site_wallets").Where("site_id = ?", siteID).Delete(nil).Error
|
||||
_ = tx.Where("distribution_site_id = ?", siteID).Delete(&model.WalletAccount{}).Error
|
||||
// 分销余额保存在 wallet_accounts,不存在独立的 distribution_site_wallets 表。
|
||||
if err := tx.Where("distribution_site_id = ?", siteID).Delete(&model.WalletAccount{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除站点主体
|
||||
if err := tx.Delete(&site).Error; err != nil {
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package distribution
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
@@ -58,6 +61,91 @@ func TestSiteCRUD_UpdateSiteAndDomainUniqueness(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteSiteProtectsAllNonzeroWalletBalances(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
site, err := repo.CreateSite(t.Context(), CreateSiteRequest{SiteCode: "wallet_guard", SiteName: "余额保护"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wallet := model.WalletAccount{UserID: 7, DistributionSiteID: site.ID}
|
||||
if err := db.Create(&wallet).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, balance := range []struct{ available, frozen int64 }{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
|
||||
if err := db.Model(&wallet).Updates(map[string]any{"available_balance_cent": balance.available, "frozen_balance_cent": balance.frozen}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.DeleteSite(t.Context(), 0, site.ID); err == nil {
|
||||
t.Fatalf("deleted site with balance %+v", balance)
|
||||
}
|
||||
}
|
||||
if err := db.Model(&wallet).Updates(map[string]any{"available_balance_cent": 0, "frozen_balance_cent": 0}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := repo.DeleteSite(t.Context(), 0, site.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteSiteRollsBackOnWalletCleanupFailure(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
onboard, err := repo.OnboardSite(t.Context(), OnboardSiteRequest{
|
||||
SiteCode: "rollback_site", SiteName: "回滚站点", Domain: "rollback.test",
|
||||
AdminUsername: "rollback_admin", AdminPassword: "password123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
siteID := onboard.Site.ID
|
||||
role := model.Role{Code: "cleanup_test_role", Name: "清理测试角色"}
|
||||
if err := db.Create(&role).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.AdminUserRole{AdminID: onboard.Member.AdminID, RoleID: role.ID}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.DistributionRuleVersion{SiteID: &siteID, Mode: "A", Version: 1, Status: "active", EffectiveFrom: time.Now()}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.WalletAccount{UserID: 7, DistributionSiteID: siteID}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantErr := errors.New("wallet cleanup failed")
|
||||
const callback = "test:fail_wallet_cleanup"
|
||||
if err := db.Callback().Delete().Before("gorm:delete").Register(callback, func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "wallet_accounts" {
|
||||
tx.AddError(wantErr)
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { db.Callback().Delete().Remove(callback) })
|
||||
if err := repo.DeleteSite(t.Context(), 0, siteID); !errors.Is(err, wantErr) {
|
||||
t.Fatalf("DeleteSite error = %v, want injected failure", err)
|
||||
}
|
||||
for _, item := range []struct {
|
||||
table, predicate string
|
||||
id uint64
|
||||
}{
|
||||
{"distribution_sites", "id = ?", siteID},
|
||||
{"distribution_site_members", "site_id = ?", siteID},
|
||||
{"distribution_rule_versions", "site_id = ?", siteID},
|
||||
{"admin_users", "id = ?", onboard.Member.AdminID},
|
||||
{"admin_user_roles", "admin_user_id = ?", onboard.Member.AdminID},
|
||||
{"wallet_accounts", "distribution_site_id = ?", siteID},
|
||||
} {
|
||||
var count int64
|
||||
if err := db.Table(item.table).Where(item.predicate, item.id).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count == 0 {
|
||||
t.Errorf("%s was not rolled back", item.table)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSiteCRUD_DeleteSiteProtectionAndCascade(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
repo := NewRepository(db)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"hfb_sys/backend/internal/filekey"
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chat"
|
||||
"hfb_sys/backend/internal/modules/distribution"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type distributionQrCodeScopeKey struct{}
|
||||
type distributionQrCodeScope struct {
|
||||
AdminID, SiteID, TenantID uint64
|
||||
}
|
||||
|
||||
// 独立分销后台只开放读取,不复用经营站的二维码管理权限。
|
||||
func registerDistributionQrCodeRoutes(routes *gin.RouterGroup, db *gorm.DB, service *distribution.Service, chats *chat.Handler, image gin.HandlerFunc) {
|
||||
scoped := routes.Group("/sites/:id/qrcodes", requireDistributionQrCodeScope(db, service))
|
||||
scoped.GET("", chats.ListSiteQrCodesHandler)
|
||||
scoped.GET("/stats", chats.GetSiteQrCodeStatsHandler)
|
||||
scoped.GET("/:qrcodeId/image", distributionQrCodeImage(db, image))
|
||||
}
|
||||
|
||||
func requireDistributionQrCodeScope(db *gorm.DB, service *distribution.Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
adminID := c.GetUint64(middleware.ContextAdminID)
|
||||
if adminID == 0 {
|
||||
response.Error(c, http.StatusUnauthorized, "unauthorized", "请先登录")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
siteID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil || siteID == 0 {
|
||||
response.BadRequest(c, "分销站点编号不正确")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if db == nil || service == nil {
|
||||
response.ServiceUnavailable(c, "二维码查询暂时不可用")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if _, err := service.ScopeSiteID(ctx, adminID, siteID); err != nil {
|
||||
if errors.Is(err, distribution.ErrSiteAccessDenied) {
|
||||
response.Error(c, http.StatusForbidden, "forbidden", "无权访问该分销站点")
|
||||
} else {
|
||||
response.RecordError(c, err)
|
||||
response.ServiceUnavailable(c, "站点权限校验失败")
|
||||
}
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
var owner struct {
|
||||
SiteCode string
|
||||
TenantID uint64
|
||||
}
|
||||
err = db.WithContext(ctx).Table("distribution_sites AS ds").
|
||||
Select("ds.site_code, st.tenant_id").
|
||||
Joins("JOIN chat_site_tenant_links st ON st.site_id = ds.id AND st.enabled = 1").
|
||||
Joins("JOIN tenants t ON t.id = st.tenant_id AND t.status = 'active'").
|
||||
Where("ds.id = ? AND ds.status = 'active'", siteID).Take(&owner).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.RecordError(c, err)
|
||||
response.ServiceUnavailable(c, "站点归属查询失败")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
boundCode := sitecode.BoundSiteCodeFromContext(ctx)
|
||||
requestTenant := tenancy.IDFromContext(ctx)
|
||||
if err != nil || owner.TenantID == 0 ||
|
||||
(boundCode != "" && boundCode != owner.SiteCode) ||
|
||||
(requestTenant != 0 && requestTenant != owner.TenantID) {
|
||||
response.Error(c, http.StatusForbidden, "forbidden", "无权访问该站点二维码池")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
scope, _ := tenancy.FromContext(ctx)
|
||||
scope.TenantID = owner.TenantID
|
||||
ctx = tenancy.WithScope(ctx, scope)
|
||||
ctx = context.WithValue(ctx, distributionQrCodeScopeKey{}, distributionQrCodeScope{adminID, siteID, owner.TenantID})
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
type distributionQrCodeImageKey struct{}
|
||||
type distributionQrCodeImageGrant struct {
|
||||
AdminID uint64
|
||||
Key string
|
||||
}
|
||||
|
||||
// 图片编号在服务端解析,客户端不能借图片 URL 读取其他站点的私有对象。
|
||||
func distributionQrCodeImage(db *gorm.DB, object gin.HandlerFunc) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
scope, ok := ctx.Value(distributionQrCodeScopeKey{}).(distributionQrCodeScope)
|
||||
if !ok || scope.AdminID == 0 {
|
||||
response.Error(c, http.StatusForbidden, "forbidden", "无权访问该二维码")
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseUint(c.Param("qrcodeId"), 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
response.BadRequest(c, "二维码编号不正确")
|
||||
return
|
||||
}
|
||||
var code model.ChatQrCode
|
||||
err = db.WithContext(ctx).Select("id, image_url").
|
||||
Where("id = ? AND distribution_site_id = ? AND tenant_id = ?", id, scope.SiteID, scope.TenantID).Take(&code).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
response.Error(c, http.StatusNotFound, "not_found", "二维码不存在")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.ServiceUnavailable(c, "二维码图片查询失败")
|
||||
return
|
||||
}
|
||||
key := filekey.Canonical(code.ImageURL)
|
||||
if key == "" {
|
||||
response.Error(c, http.StatusNotFound, "not_found", "二维码图片暂不可用")
|
||||
return
|
||||
}
|
||||
ctx = context.WithValue(ctx, distributionQrCodeImageKey{}, distributionQrCodeImageGrant{scope.AdminID, key})
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
query := c.Request.URL.Query()
|
||||
query.Set("key", key)
|
||||
query.Del("ticket")
|
||||
c.Request.URL.RawQuery = query.Encode()
|
||||
object(c)
|
||||
}
|
||||
}
|
||||
|
||||
func distributionQrCodeImageAuthorizer(ctx context.Context, adminID uint64, key string) (bool, error) {
|
||||
grant, ok := ctx.Value(distributionQrCodeImageKey{}).(distributionQrCodeImageGrant)
|
||||
return ok && adminID > 0 && adminID == grant.AdminID && key == grant.Key, nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/chat"
|
||||
"hfb_sys/backend/internal/modules/distribution"
|
||||
"hfb_sys/backend/internal/sitecode"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func distributionQrCodeTestRouter(t *testing.T) (*gin.Engine, *gorm.DB) {
|
||||
t.Helper()
|
||||
db := database.NewTestDB()
|
||||
siteA, siteB := uint64(11), uint64(12)
|
||||
conversationID := uint64(201)
|
||||
now, expired := time.Now(), time.Now().Add(-time.Hour)
|
||||
for _, records := range []any{
|
||||
&[]model.Tenant{{ID: 41, Code: "qr_parent", Name: "大锤", Status: "active"}, {ID: 42, Code: "qr_other", Name: "其他经营站", Status: "active"}},
|
||||
&[]model.AdminUser{{ID: 7, Username: "qr_member", Status: "active"}, {ID: 8, Username: "qr_disabled_member", Status: "active"}, {ID: 9, Username: "qr_super", Status: "active"}},
|
||||
&[]model.DistributionSite{{ID: siteA, SiteCode: "gz_dist", SiteName: "天域", Domain: "qr-a.test", Status: "active"}, {ID: siteB, SiteCode: "other_dist", SiteName: "其他分站", Domain: "qr-b.test", Status: "active"}},
|
||||
&[]model.ChatSiteTenantLink{{SiteID: siteA, TenantID: 41, Enabled: true}, {SiteID: siteB, TenantID: 41, Enabled: true}},
|
||||
&[]model.DistributionSiteMember{{SiteID: siteA, AdminUserID: 7, MemberType: "owner", Status: "active"}, {SiteID: siteA, AdminUserID: 8, MemberType: "owner", Status: "disabled"}},
|
||||
&model.ChatConversation{ID: conversationID, TenantID: 41, DistributionSiteID: &siteA, Title: "账号群 202611290372"},
|
||||
&[]model.ChatQrCode{
|
||||
{ID: 101, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "/api/admin/files/object?key=qrcode%2Fown.jpg", GroupName: "天域商行对接群115", Status: "unused", CreatedBy: 7},
|
||||
{ID: 102, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "qrcode/used.jpg", GroupName: "天域商行对接群116", Status: "used", ConversationID: &conversationID, UsedAt: &now, CreatedBy: 7},
|
||||
{ID: 103, TenantID: 41, DistributionSiteID: &siteB, ImageURL: "qrcode/other-site.jpg", Status: "unused", CreatedBy: 7},
|
||||
{ID: 104, TenantID: 42, DistributionSiteID: &siteA, ImageURL: "qrcode/other-tenant.jpg", Status: "unused", CreatedBy: 7},
|
||||
{ID: 105, TenantID: 41, ImageURL: "qrcode/main-site.jpg", Status: "unused", CreatedBy: 7},
|
||||
{ID: 106, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "qrcode/disabled.jpg", Status: "disabled", CreatedBy: 7},
|
||||
{ID: 107, TenantID: 41, DistributionSiteID: &siteA, ImageURL: "qrcode/expired.jpg", Status: "unused", ExpiresAt: &expired, CreatedBy: 7},
|
||||
},
|
||||
&model.Role{ID: 91, Code: "super_admin", Name: "平台超管"},
|
||||
&model.AdminUserRole{AdminID: 9, RoleID: 91},
|
||||
} {
|
||||
if err := db.Create(records).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
engine := gin.New()
|
||||
group := engine.Group("/distribution", func(c *gin.Context) {
|
||||
adminID, _ := strconv.ParseUint(c.GetHeader("X-Test-Admin"), 10, 64)
|
||||
c.Set(middleware.ContextAdminID, adminID)
|
||||
tenantID, _ := strconv.ParseUint(c.GetHeader("X-Test-Tenant"), 10, 64)
|
||||
ctx := tenancy.WithScope(c.Request.Context(), tenancy.Scope{TenantID: tenantID})
|
||||
ctx = sitecode.WithBoundSiteCode(ctx, c.GetHeader("X-Test-Site"))
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
})
|
||||
registerDistributionQrCodeRoutes(group, db, distribution.NewService(distribution.NewRepository(db)),
|
||||
chat.NewHandler(chat.NewService(chat.NewRepository(db, nil, nil))), func(c *gin.Context) {
|
||||
allowed, err := distributionQrCodeImageAuthorizer(c.Request.Context(), c.GetUint64(middleware.ContextAdminID), c.Query("key"))
|
||||
if err != nil || !allowed {
|
||||
t.Error("verified image grant rejected")
|
||||
}
|
||||
if allowed, _ := distributionQrCodeImageAuthorizer(c.Request.Context(), 99, c.Query("key")); allowed {
|
||||
t.Error("image grant allowed another admin")
|
||||
}
|
||||
if allowed, _ := distributionQrCodeImageAuthorizer(c.Request.Context(), 7, "qrcode/other-site.jpg"); allowed {
|
||||
t.Error("image grant allowed another key")
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"key": c.Query("key"), "tenant_id": tenancy.IDFromContext(c.Request.Context())})
|
||||
})
|
||||
return engine, db
|
||||
}
|
||||
|
||||
func TestDistributionQrCodeReadRoutes(t *testing.T) {
|
||||
engine, db := distributionQrCodeTestRouter(t)
|
||||
request := func(path string, adminID, tenantID uint64, boundSite string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(http.MethodGet, "/distribution/sites/"+path, nil)
|
||||
r.Header.Set("X-Test-Admin", fmt.Sprint(adminID))
|
||||
r.Header.Set("X-Test-Tenant", fmt.Sprint(tenantID))
|
||||
r.Header.Set("X-Test-Site", boundSite)
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
name, path string
|
||||
adminID, tenantID uint64
|
||||
boundSite string
|
||||
want int
|
||||
}{
|
||||
{"tenantless_member", "11/qrcodes", 7, 0, "", 200},
|
||||
{"parent_tenant_member", "11/qrcodes", 7, 41, "", 200},
|
||||
{"bound_domain", "11/qrcodes", 7, 0, "gz_dist", 200},
|
||||
{"no_login", "11/qrcodes", 0, 0, "", 401},
|
||||
{"no_member", "11/qrcodes", 99, 0, "", 403},
|
||||
{"disabled_member", "11/qrcodes", 8, 0, "", 403},
|
||||
{"other_site", "12/qrcodes", 7, 0, "", 403},
|
||||
{"other_site_stats", "12/qrcodes/stats", 7, 0, "", 403},
|
||||
{"other_tenant_host", "11/qrcodes", 7, 42, "", 403},
|
||||
{"other_bound_domain_even_superadmin", "11/qrcodes", 9, 0, "other_dist", 403},
|
||||
{"invalid_site", "0/qrcodes", 7, 0, "", 400},
|
||||
{"superadmin_selects_site", "12/qrcodes", 9, 0, "", 200},
|
||||
{"own_image_ignores_forged_key", "11/qrcodes/101/image?key=qrcode/other-site.jpg", 7, 0, "", 200},
|
||||
{"other_site_image", "11/qrcodes/103/image", 7, 0, "", 404},
|
||||
{"other_tenant_image", "11/qrcodes/104/image", 7, 0, "", 404},
|
||||
{"parent_image", "11/qrcodes/105/image", 7, 0, "", 404},
|
||||
{"other_site_image_route", "12/qrcodes/103/image", 7, 0, "", 403},
|
||||
{"invalid_image", "11/qrcodes/0/image", 7, 0, "", 400},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := request(tt.path, tt.adminID, tt.tenantID, tt.boundSite)
|
||||
if w.Code != tt.want {
|
||||
t.Fatalf("status=%d want=%d body=%s", w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
if tt.name == "own_image_ignores_forged_key" && w.Body.String() != `{"key":"qrcode/own.jpg","tenant_id":41}` {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
query string
|
||||
wantTotal int64
|
||||
wantID uint64
|
||||
}{
|
||||
{"?page=1&limit=20", 4, 107},
|
||||
{"?page=1&limit=20&keyword=202611290372", 1, 102},
|
||||
{"?page=1&limit=20&keyword=116", 1, 102},
|
||||
{"?page=1&limit=20&status=used&bound=true", 1, 102},
|
||||
{"?page=1&limit=20&bound=false", 3, 107},
|
||||
{"?page=2&limit=1", 4, 106},
|
||||
} {
|
||||
w := request("11/qrcodes"+tt.query, 7, 0, "")
|
||||
var result struct {
|
||||
Data struct {
|
||||
Items []chat.QrCodeListItem
|
||||
Total int64
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != 200 || result.Data.Total != tt.wantTotal || len(result.Data.Items) == 0 || result.Data.Items[0].ID != tt.wantID {
|
||||
t.Fatalf("query %s: %s", tt.query, w.Body.String())
|
||||
}
|
||||
for _, row := range result.Data.Items {
|
||||
if row.TenantID != 41 || row.DistributionSiteID == nil || *row.DistributionSiteID != 11 {
|
||||
t.Fatalf("cross-scope result: %+v", row)
|
||||
}
|
||||
if row.ID == 102 && row.BoundConversationTitle != "账号群 202611290372" {
|
||||
t.Fatal("missing bound group title")
|
||||
}
|
||||
}
|
||||
}
|
||||
w := request("11/qrcodes/stats", 7, 0, "")
|
||||
var stats struct{ Data chat.QrCodeStats }
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &stats); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != 200 || stats.Data != (chat.QrCodeStats{TotalCount: 4, UnusedCount: 1, UsedCount: 1, DisabledCount: 1}) {
|
||||
t.Fatalf("wrong stats: %s", w.Body.String())
|
||||
}
|
||||
if allowed, _ := distributionQrCodeImageAuthorizer(t.Context(), 7, "qrcode/own.jpg"); allowed {
|
||||
t.Fatal("image allowed without verified scope")
|
||||
}
|
||||
for _, change := range []struct {
|
||||
table, predicate string
|
||||
values map[string]any
|
||||
}{
|
||||
{"chat_site_tenant_links", "site_id = 11", map[string]any{"enabled": false}},
|
||||
{"tenants", "id = 41", map[string]any{"status": "disabled"}},
|
||||
{"distribution_sites", "id = 11", map[string]any{"status": "disabled"}},
|
||||
} {
|
||||
tx := db.Begin()
|
||||
if err := tx.Table(change.table).Where(change.predicate).Updates(change.values).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 测试路由使用同一连接池,因此提交后检查,并在下一轮恢复有效值。
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := request("11/qrcodes", 7, 0, ""); w.Code != 403 {
|
||||
t.Fatalf("inactive %s allowed: %s", change.table, w.Body.String())
|
||||
}
|
||||
if change.table == "chat_site_tenant_links" {
|
||||
change.values["enabled"] = true
|
||||
} else {
|
||||
change.values["status"] = "active"
|
||||
}
|
||||
if err := db.Table(change.table).Where(change.predicate).Updates(change.values).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, route := range engine.Routes() {
|
||||
if route.Method != http.MethodGet {
|
||||
t.Fatalf("unexpected write route: %+v", route)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -461,6 +461,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
adminPrivateFileAuthorizer(deps.DB, cfg.FileBindingMode),
|
||||
)
|
||||
fileHandler.SetAccessTicketManager(filemodule.NewAccessTicketManager(cfg.JWTSecret))
|
||||
distributionQrCodeFiles := filemodule.NewHandler(fileService, fileStorage, nil, nil, distributionQrCodeImageAuthorizer)
|
||||
listingService := listing.NewService(listingRepo, systemConfigRepo)
|
||||
listingHandler := listing.NewHandler(listingService, fileStorage, listing.HandlerOptions{
|
||||
ExternalUploadSecret: cfg.ExternalUploadSecret,
|
||||
@@ -793,6 +794,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
|
||||
distributionProtectedRoutes := api.Group("/distribution", requireAdmin)
|
||||
{
|
||||
registerDistributionQrCodeRoutes(distributionProtectedRoutes, deps.DB, distributionService, chatHandler, distributionQrCodeFiles.Object)
|
||||
distributionProtectedRoutes.GET("/auth/me", distributionHandler.Me)
|
||||
distributionProtectedRoutes.POST("/auth/logout", distributionHandler.Logout)
|
||||
distributionProtectedRoutes.POST("/sites/:id/sync-accounts", distributionHandler.SyncSiteAccounts)
|
||||
|
||||
Reference in New Issue
Block a user