feat(tenant): 按租户隔离用户身份与后台权限
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func walletTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestWalletAccountsAndLedgerAreScopedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
dachuiUser := model.User{TenantID: 101, Phone: "13400000001", Status: "active"}
|
||||
jieyouUser := model.User{TenantID: 202, Phone: "13400000001", Status: "active"}
|
||||
if err := db.Create(&dachuiUser).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&jieyouUser).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db)
|
||||
dachuiCtx := walletTenantContext(101)
|
||||
jieyouCtx := walletTenantContext(202)
|
||||
if _, err := repo.Account(dachuiCtx, dachuiUser.ID); err != nil {
|
||||
t.Fatalf("create dachui wallet: %v", err)
|
||||
}
|
||||
if _, err := repo.Account(jieyouCtx, jieyouUser.ID); err != nil {
|
||||
t.Fatalf("create jieyou wallet: %v", err)
|
||||
}
|
||||
if err := db.WithContext(dachuiCtx).Transaction(func(tx *gorm.DB) error {
|
||||
return AppendEntries(tx, Entry{
|
||||
UserID: dachuiUser.ID, Direction: "in", AmountCent: 1000,
|
||||
BalanceType: "available", BizType: "test", BizNo: "DACHUI-1",
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("append dachui ledger: %v", err)
|
||||
}
|
||||
|
||||
dachuiLedger, err := repo.Ledger(dachuiCtx, dachuiUser.ID, 1, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dachuiLedger.Total != 1 {
|
||||
t.Fatalf("dachui ledger total = %d, want 1", dachuiLedger.Total)
|
||||
}
|
||||
jieyouLedger, err := repo.Ledger(jieyouCtx, dachuiUser.ID, 1, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if jieyouLedger.Total != 0 {
|
||||
t.Fatalf("cross-tenant ledger total = %d, want 0", jieyouLedger.Total)
|
||||
}
|
||||
|
||||
var accounts []model.WalletAccount
|
||||
if err := db.Order("id ASC").Find(&accounts).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(accounts) != 2 || accounts[0].TenantID != 101 || accounts[1].TenantID != 202 {
|
||||
t.Fatalf("tenant wallet accounts = %+v", accounts)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user