feat(tenant): 按租户隔离用户身份与后台权限

This commit is contained in:
yml
2026-11-15 15:37:23 +08:00
parent ca57f604bf
commit abf0fce89b
43 changed files with 1572 additions and 196 deletions
+60 -19
View File
@@ -8,6 +8,7 @@ import (
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/modules/auth"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
@@ -78,6 +79,11 @@ func Auth(jwtManager *auth.JWTManager, validate UserTokenValidatorFunc) gin.Hand
c.Abort()
return
}
if !userTokenTenantMatches(c, claims.TenantID) {
response.Unauthorized(c, "访问令牌不属于当前站点")
c.Abort()
return
}
if validate != nil {
if err := validate(c.Request.Context(), claims.UserID, claims.TokenVersion); err != nil {
if errors.Is(err, auth.ErrDependencyUnavailable) {
@@ -114,6 +120,10 @@ func OptionalAuth(jwtManager *auth.JWTManager, validate UserTokenValidatorFunc)
c.Next()
return
}
if !userTokenTenantMatches(c, claims.TenantID) {
c.Next()
return
}
if validate != nil {
if err := validate(c.Request.Context(), claims.UserID, claims.TokenVersion); err != nil {
c.Next()
@@ -132,26 +142,30 @@ func AuthUserOrAdmin(jwtManager *auth.JWTManager, userValidate UserTokenValidato
// 1. 优先尝试管理员鉴权(Header Bearer 或 Admin Cookie)
if tokenText, tokenSource := extractAdminToken(c); tokenText != "" {
if claims, err := jwtManager.ParseSubject(tokenText, "access", "admin"); err == nil {
username := claims.Phone
passwordMustChange := false
validAdmin := true
if adminValidate != nil {
tokenContext, err := adminValidate(c.Request.Context(), claims.UserID, claims.TokenVersion)
if err != nil {
RecordAdminAuthFailure(c, "invalid", tokenSource, 0, 0)
validAdmin = false
} else {
username = tokenContext.Username
passwordMustChange = tokenContext.PasswordMustChange
if !adminTokenTenantMatches(c, claims.TenantID) {
RecordAdminAuthFailure(c, "tenant_mismatch", tokenSource, 0, 0)
} else {
username := claims.Phone
passwordMustChange := false
validAdmin := true
if adminValidate != nil {
tokenContext, err := adminValidate(c.Request.Context(), claims.UserID, claims.TokenVersion)
if err != nil {
RecordAdminAuthFailure(c, "invalid", tokenSource, 0, 0)
validAdmin = false
} else {
username = tokenContext.Username
passwordMustChange = tokenContext.PasswordMustChange
}
}
if validAdmin {
c.Set(ContextAdminID, claims.UserID)
c.Request = c.Request.WithContext(logging.WithAdminID(c.Request.Context(), claims.UserID))
c.Set(ContextUsername, username)
c.Set(ContextPasswordMustChange, passwordMustChange)
c.Next()
return
}
}
if validAdmin {
c.Set(ContextAdminID, claims.UserID)
c.Request = c.Request.WithContext(logging.WithAdminID(c.Request.Context(), claims.UserID))
c.Set(ContextUsername, username)
c.Set(ContextPasswordMustChange, passwordMustChange)
c.Next()
return
}
}
}
@@ -175,6 +189,11 @@ func AuthUserOrAdmin(jwtManager *auth.JWTManager, userValidate UserTokenValidato
c.Abort()
return
}
if !userTokenTenantMatches(c, claims.TenantID) {
response.Unauthorized(c, "访问令牌不属于当前站点")
c.Abort()
return
}
if userValidate != nil {
if err := userValidate(c.Request.Context(), claims.UserID, claims.TokenVersion); err != nil {
if errors.Is(err, auth.ErrDependencyUnavailable) {
@@ -193,6 +212,14 @@ func AuthUserOrAdmin(jwtManager *auth.JWTManager, userValidate UserTokenValidato
}
}
func userTokenTenantMatches(c *gin.Context, tokenTenantID uint64) bool {
requestTenantID := tenancy.IDFromContext(c.Request.Context())
if tokenTenantID == 0 {
return true
}
return requestTenantID > 0 && requestTenantID == tokenTenantID
}
func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gin.HandlerFunc {
return func(c *gin.Context) {
tokenText, tokenSource := extractAdminToken(c)
@@ -210,6 +237,12 @@ func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gi
c.Abort()
return
}
if !adminTokenTenantMatches(c, claims.TenantID) {
RecordAdminAuthFailure(c, "tenant_mismatch", tokenSource, 0, 0)
response.Unauthorized(c, "后台访问令牌不属于当前站点")
c.Abort()
return
}
c.Set(ContextAdminID, claims.UserID)
c.Request = c.Request.WithContext(logging.WithAdminID(c.Request.Context(), claims.UserID))
username := claims.Phone
@@ -238,6 +271,14 @@ func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gi
}
}
func adminTokenTenantMatches(c *gin.Context, tokenTenantID uint64) bool {
requestTenantID := tenancy.IDFromContext(c.Request.Context())
if tokenTenantID == 0 {
return true
}
return requestTenantID > 0 && requestTenantID == tokenTenantID
}
type authFailureReasonCarrier interface {
AuthFailureReason() string
}
+48
View File
@@ -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)
}
}
+11 -1
View File
@@ -1,11 +1,13 @@
package middleware
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
@@ -89,7 +91,7 @@ func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64) ([]string,
if rdb == nil {
return nil, errors.New("redis unavailable")
}
key := fmt.Sprintf("admin:perms:%d", adminID)
key := adminPermissionCacheKey(c.Request.Context(), adminID)
raw, err := rdb.Get(c.Request.Context(), key).Result()
if errors.Is(err, redis.Nil) {
return nil, nil // 缓存未命中,视为无权限
@@ -103,3 +105,11 @@ func getPermCodes(c *gin.Context, rdb *redis.Client, adminID uint64) ([]string,
}
return codes, nil
}
func adminPermissionCacheKey(ctx context.Context, adminID uint64) string {
key := fmt.Sprintf("admin:perms:%d", adminID)
if scope := tenancy.ScopeKey(ctx); scope != "" {
key += ":" + scope
}
return key
}
@@ -9,10 +9,22 @@ import (
"testing"
"time"
"hfb_sys/backend/internal/tenancy"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
)
func TestAdminPermissionCacheKeyIncludesTenant(t *testing.T) {
ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 101})
if got := adminPermissionCacheKey(ctx, 7); got != "admin:perms:7:tenant:101" {
t.Fatalf("tenant permission cache key = %q", got)
}
if got := adminPermissionCacheKey(context.Background(), 7); got != "admin:perms:7" {
t.Fatalf("legacy permission cache key = %q", got)
}
}
func TestRequireAnyPermission(t *testing.T) {
gin.SetMode(gin.TestMode)
rdb := redis.NewClient(&redis.Options{
+13 -2
View File
@@ -23,11 +23,15 @@ type TenantResolver interface {
ResolveCode(ctx context.Context, code string) (*tenancy.Scope, error)
}
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) gin.HandlerFunc {
func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger, defaultTenantCodes ...string) gin.HandlerFunc {
if resolver == nil {
return func(c *gin.Context) { c.Next() }
}
production := config.IsProductionEnv(appEnv)
defaultTenantCode := ""
if len(defaultTenantCodes) > 0 {
defaultTenantCode = strings.TrimSpace(defaultTenantCodes[0])
}
return func(c *gin.Context) {
var (
scope *tenancy.Scope
@@ -42,9 +46,16 @@ func TenantContext(resolver TenantResolver, appEnv string, logger *zap.Logger) g
if scope == nil && err == nil {
scope, err = resolver.ResolveHost(c.Request.Context(), c.Request.Host)
}
host := sitecode.ExtractHost(c.Request.Host)
if scope == nil && err == nil && defaultTenantCode != "" && sitecode.FromRequest(c) != "" {
scope, err = resolver.ResolveCode(c.Request.Context(), defaultTenantCode)
}
if scope == nil && err == nil && !production && sitecode.IsLocalHost(host) && defaultTenantCode != "" {
scope, err = resolver.ResolveCode(c.Request.Context(), defaultTenantCode)
}
if err != nil && logger != nil {
logger.Warn("经营租户解析失败,按旧站点上下文继续",
zap.String("host", sitecode.ExtractHost(c.Request.Host)),
zap.String("host", host),
zap.Error(err),
)
}
+2 -1
View File
@@ -8,7 +8,8 @@ import (
type UserPaymentAccount struct {
ID uint64 `gorm:"primaryKey" json:"id"`
UserID uint64 `gorm:"not null;index" json:"user_id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_user_payment_accounts_tenant_user" json:"tenant_id"`
UserID uint64 `gorm:"not null;index:idx_user_payment_accounts_tenant_user" json:"user_id"`
AccountType string `gorm:"size:32;not null" json:"account_type"`
AccountName string `gorm:"size:128;not null" json:"account_name"`
AccountNo string `gorm:"size:255;not null" json:"account_no"`
+3 -2
View File
@@ -27,8 +27,9 @@ func (Permission) TableName() string { return "permissions" }
type AdminUserRole struct {
ID uint64 `gorm:"primaryKey" json:"id"`
AdminID uint64 `gorm:"column:admin_user_id;not null;uniqueIndex:uk_admin_user_roles_user_role" json:"admin_id"`
RoleID uint64 `gorm:"column:role_id;not null;uniqueIndex:uk_admin_user_roles_user_role" json:"role_id"`
AdminID uint64 `gorm:"column:admin_user_id;not null;uniqueIndex:uk_admin_user_roles_tenant_user_role;index:idx_admin_user_roles_tenant_admin" json:"admin_id"`
RoleID uint64 `gorm:"column:role_id;not null;uniqueIndex:uk_admin_user_roles_tenant_user_role" json:"role_id"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_admin_user_roles_tenant_user_role;index:idx_admin_user_roles_tenant_admin" json:"tenant_id"`
CreatedAt time.Time `json:"created_at"`
}
+3 -2
View File
@@ -4,7 +4,8 @@ import "time"
type User struct {
ID uint64 `gorm:"primaryKey" json:"id"`
Phone string `gorm:"size:32;not null;uniqueIndex" json:"phone"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_users_tenant_phone;index:idx_users_tenant_status" json:"tenant_id"`
Phone string `gorm:"size:32;not null;uniqueIndex:uk_users_tenant_phone" json:"phone"`
PasswordHash string `gorm:"size:255;not null;default:''" json:"-"`
Nickname string `gorm:"size:64;not null;default:''" json:"nickname"`
AvatarURL string `gorm:"size:512;not null;default:''" json:"avatar_url"`
@@ -27,7 +28,7 @@ type User struct {
// 注册归因:注册时由前端携带的推广短码。
RegisterTrackCode string `gorm:"size:64;index:idx_users_register_track_code" json:"register_track_code,omitempty"`
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_users_distribution_site_id" json:"distribution_site_id"` // 0=主站, >0=对应分销站点
InviteCode *string `gorm:"size:32;uniqueIndex:uk_users_invite_code" json:"invite_code,omitempty"`
InviteCode *string `gorm:"size:32;uniqueIndex:uk_users_tenant_invite_code" json:"invite_code,omitempty"`
InvitedByID uint64 `gorm:"not null;default:0;index:idx_users_invited_by_id" json:"invited_by_id,omitempty"`
InviteVerifiedAt *time.Time `json:"invite_verified_at,omitempty"`
LastLoginAt *time.Time `json:"last_login_at"`
+3 -2
View File
@@ -4,7 +4,8 @@ import "time"
type UserRealname struct {
ID uint64 `gorm:"primaryKey" json:"id"`
UserID uint64 `gorm:"not null;uniqueIndex" json:"user_id"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_user_realname_tenant_user;index:idx_user_realname_tenant_user" json:"tenant_id"`
UserID uint64 `gorm:"not null;uniqueIndex:uk_user_realname_tenant_user" json:"user_id"`
Provider string `gorm:"size:32;not null" json:"provider"`
ProviderOrderNo string `gorm:"size:128;not null;default:''" json:"provider_order_no"`
Status string `gorm:"size:32;not null;default:'pending'" json:"status"`
@@ -13,7 +14,7 @@ type UserRealname struct {
MaskedIDNo string `gorm:"size:64;not null;default:'';index:idx_user_realname_masked_id_no" json:"masked_id_no"`
EncryptedIDNo string `gorm:"size:255;not null;default:''" json:"encrypted_id_no"`
// IDNoHash 是身份证号的不可逆指纹,仅认证通过时写入;唯一索引保证同一身份证只能绑定一个账号。
IDNoHash *string `gorm:"size:64;uniqueIndex:uk_user_realname_id_no_hash" json:"-"`
IDNoHash *string `gorm:"size:64;uniqueIndex:uk_user_realname_tenant_id_no" json:"-"`
VerifiedAt *time.Time `json:"verified_at"`
FailReason string `gorm:"size:255;not null;default:''" json:"fail_reason"`
CreatedAt time.Time `json:"created_at"`
+5 -3
View File
@@ -4,8 +4,9 @@ import "time"
type WalletAccount struct {
ID uint64 `gorm:"primaryKey" json:"id"`
UserID uint64 `gorm:"not null;uniqueIndex:uk_wallet_accounts_user_site" json:"user_id"`
DistributionSiteID uint64 `gorm:"not null;default:0;uniqueIndex:uk_wallet_accounts_user_site" json:"distribution_site_id"`
TenantID uint64 `gorm:"not null;default:0;uniqueIndex:uk_wallet_accounts_tenant_user_site;index:idx_wallet_accounts_tenant_user" json:"tenant_id"`
UserID uint64 `gorm:"not null;uniqueIndex:uk_wallet_accounts_tenant_user_site" json:"user_id"`
DistributionSiteID uint64 `gorm:"not null;default:0;uniqueIndex:uk_wallet_accounts_tenant_user_site" json:"distribution_site_id"`
AvailableBalanceCent int64 `gorm:"not null;default:0" json:"-"`
FrozenBalanceCent int64 `gorm:"not null;default:0" json:"-"`
Status string `gorm:"size:32;not null;default:'active'" json:"status"`
@@ -20,7 +21,8 @@ func (WalletAccount) TableName() string {
type WalletLedger struct {
ID uint64 `gorm:"primaryKey" json:"id"`
LedgerNo string `gorm:"size:64;not null;uniqueIndex" json:"ledger_no"`
UserID uint64 `gorm:"not null;index:idx_wallet_ledger_user_site" json:"user_id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_wallet_ledger_tenant_user_created" json:"tenant_id"`
UserID uint64 `gorm:"not null;index:idx_wallet_ledger_user_site;index:idx_wallet_ledger_tenant_user_created" json:"user_id"`
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_wallet_ledger_user_site" json:"distribution_site_id"`
OrderID *uint64 `json:"order_id"`
Direction string `gorm:"size:16;not null" json:"direction"`
+2 -1
View File
@@ -5,7 +5,8 @@ import "time"
type WithdrawalRequest struct {
ID uint64 `gorm:"primaryKey" json:"id"`
WithdrawNo string `gorm:"size:64;not null;uniqueIndex" json:"withdraw_no"`
UserID uint64 `gorm:"not null;index:idx_withdrawal_user_site" json:"user_id"`
TenantID uint64 `gorm:"not null;default:0;index:idx_withdrawal_tenant_user_created" json:"tenant_id"`
UserID uint64 `gorm:"not null;index:idx_withdrawal_user_site;index:idx_withdrawal_tenant_user_created" json:"user_id"`
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_withdrawal_user_site" json:"distribution_site_id"`
AmountCent int64 `gorm:"not null;default:0" json:"-"`
FeeCent int64 `gorm:"not null;default:0" json:"-"`
@@ -8,6 +8,7 @@ import (
type AdminDTO struct {
ID uint64 `json:"id"`
TenantID uint64 `json:"tenant_id"`
Username string `json:"username"`
Nickname string `json:"nickname"`
Status string `json:"status"`
@@ -13,6 +13,7 @@ import (
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/auth"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"golang.org/x/crypto/bcrypt"
@@ -52,16 +53,17 @@ func (r *Repository) Captcha(ctx context.Context) (*CaptchaDTO, error) {
}
func (r *Repository) Login(ctx context.Context, username string, password string, captchaID string, captchaCode string, clientIP string) (LoginResult, error) {
tenantID := tenancy.IDFromContext(ctx)
if err := r.verifyCaptcha(ctx, captchaID, captchaCode); err != nil {
return LoginResult{}, err
}
if err := r.ensureLoginNotLocked(ctx, username, clientIP); err != nil {
if err := r.ensureLoginNotLocked(ctx, tenantID, username, clientIP); err != nil {
return LoginResult{}, err
}
var admin model.AdminUser
if err := r.db.WithContext(ctx).Where("username = ?", username).First(&admin).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
r.recordLoginFailure(ctx, username, clientIP)
r.recordLoginFailure(ctx, tenantID, username, clientIP)
return LoginResult{}, ErrInvalidCredential
}
return LoginResult{}, err
@@ -70,7 +72,15 @@ func (r *Repository) Login(ctx context.Context, username string, password string
return LoginResult{}, ErrAdminDisabled
}
if err := bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(password)); err != nil {
r.recordLoginFailure(ctx, username, clientIP)
r.recordLoginFailure(ctx, tenantID, username, clientIP)
return LoginResult{}, ErrInvalidCredential
}
allowed, err := r.adminHasTenantAccess(ctx, admin.ID)
if err != nil {
return LoginResult{}, err
}
if !allowed {
r.recordLoginFailure(ctx, tenantID, username, clientIP)
return LoginResult{}, ErrInvalidCredential
}
now := time.Now()
@@ -81,12 +91,13 @@ func (r *Repository) Login(ctx context.Context, username string, password string
if err := r.db.WithContext(ctx).Save(&admin).Error; err != nil {
return LoginResult{}, err
}
r.clearLoginFailures(ctx, username, clientIP)
tokens, err := r.jwt.GenerateSubjectPairWithVersion(admin.ID, admin.Username, "admin", admin.TokenVersion)
r.clearLoginFailures(ctx, tenantID, username, clientIP)
tokens, err := r.jwt.GenerateTenantPairWithVersion(admin.ID, admin.Username, "admin", admin.TokenVersion, tenantID)
if err != nil {
return LoginResult{}, err
}
dto := toDTO(admin)
dto.TenantID = tenantID
r.loadRolesAndPerms(ctx, &dto)
return LoginResult{Admin: dto, Tokens: tokens}, nil
}
@@ -108,6 +119,13 @@ func (r *Repository) FindActiveForToken(ctx context.Context, id uint64, tokenVer
if admin.TokenVersion <= 0 || admin.TokenVersion != tokenVersion {
return nil, newTokenVersionMismatchError(tokenVersion, admin.TokenVersion)
}
allowed, err := r.adminHasTenantAccess(ctx, admin.ID)
if err != nil {
return nil, newTokenDependencyError(err)
}
if !allowed {
return nil, newTokenValidationError("admin_tenant_forbidden", ErrAdminNotFound)
}
return &admin, nil
}
@@ -158,6 +176,7 @@ func (r *Repository) FindByID(ctx context.Context, id uint64) (*AdminDTO, error)
return nil, ErrAdminDisabled
}
dto := toDTO(admin)
dto.TenantID = tenancy.IDFromContext(ctx)
r.loadRolesAndPerms(ctx, &dto)
return &dto, nil
}
@@ -204,10 +223,13 @@ func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) {
}
// 加载角色
var roles []RoleDTO
r.db.WithContext(ctx).Table("roles").
roleQuery := r.db.WithContext(ctx).Table("roles").
Joins("JOIN admin_user_roles aur ON aur.role_id = roles.id").
Where("aur.admin_user_id = ?", dto.ID).
Find(&roles)
Where("aur.admin_user_id = ?", dto.ID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
roleQuery = roleQuery.Where("(aur.tenant_id = ? OR roles.code = ?)", tenantID, "super_admin")
}
roleQuery.Find(&roles)
dto.Roles = roles
dto.PasswordMustChange = dto.PasswordMustChange && rolesRequireInitialPasswordChange(roles)
@@ -221,12 +243,15 @@ func (r *Repository) loadRolesAndPerms(ctx context.Context, dto *AdminDTO) {
}
var permCodes []string
r.db.WithContext(ctx).Table("permissions").
permQuery := r.db.WithContext(ctx).Table("permissions").
Select("DISTINCT permissions.code").
Joins("JOIN role_permissions rp ON rp.permission_id = permissions.id").
Joins("JOIN admin_user_roles aur ON aur.role_id = rp.role_id").
Where("aur.admin_user_id = ?", dto.ID).
Pluck("code", &permCodes)
Where("aur.admin_user_id = ?", dto.ID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
permQuery = permQuery.Where("aur.tenant_id = ?", tenantID)
}
permQuery.Pluck("code", &permCodes)
dto.Permissions = permCodes
// 缓存权限到 Redis
@@ -246,16 +271,16 @@ func cachePermissions(ctx context.Context, r *Repository, adminID uint64, permCo
if r.redis == nil || len(permCodes) == 0 {
return
}
key := fmt.Sprintf("admin:perms:%d", adminID)
key := adminPermissionCacheKey(ctx, adminID)
raw, _ := json.Marshal(permCodes)
r.redis.Set(ctx, key, string(raw), 2*time.Hour)
}
func (r *Repository) ensureLoginNotLocked(ctx context.Context, username string, clientIP string) error {
func (r *Repository) ensureLoginNotLocked(ctx context.Context, tenantID uint64, username string, clientIP string) error {
if r.redis == nil {
return nil
}
locked, err := r.redis.Exists(ctx, loginLockKey(username, clientIP)).Result()
locked, err := r.redis.Exists(ctx, loginLockKey(tenantID, username, clientIP)).Result()
if err != nil {
return err
}
@@ -265,11 +290,11 @@ func (r *Repository) ensureLoginNotLocked(ctx context.Context, username string,
return nil
}
func (r *Repository) recordLoginFailure(ctx context.Context, username string, clientIP string) {
func (r *Repository) recordLoginFailure(ctx context.Context, tenantID uint64, username string, clientIP string) {
if r.redis == nil {
return
}
key := loginFailureKey(username, clientIP)
key := loginFailureKey(tenantID, username, clientIP)
count, err := r.redis.Incr(ctx, key).Result()
if err != nil {
return
@@ -278,23 +303,51 @@ func (r *Repository) recordLoginFailure(ctx context.Context, username string, cl
_ = r.redis.Expire(ctx, key, loginFailureTTL).Err()
}
if count >= loginMaxFailureCount {
_ = r.redis.Set(ctx, loginLockKey(username, clientIP), "1", loginLockTTL).Err()
_ = r.redis.Set(ctx, loginLockKey(tenantID, username, clientIP), "1", loginLockTTL).Err()
}
}
func (r *Repository) clearLoginFailures(ctx context.Context, username string, clientIP string) {
func (r *Repository) clearLoginFailures(ctx context.Context, tenantID uint64, username string, clientIP string) {
if r.redis == nil {
return
}
_ = r.redis.Del(ctx, loginFailureKey(username, clientIP), loginLockKey(username, clientIP)).Err()
_ = r.redis.Del(ctx, loginFailureKey(tenantID, username, clientIP), loginLockKey(tenantID, username, clientIP)).Err()
}
func loginFailureKey(username string, clientIP string) string {
return "admin:login:fail:" + loginKeyPart(clientIP) + ":" + loginKeyPart(username)
func loginFailureKey(tenantID uint64, username string, clientIP string) string {
return scopedAuthKey(tenantID, "admin:login:fail:"+loginKeyPart(clientIP)+":"+loginKeyPart(username))
}
func loginLockKey(username string, clientIP string) string {
return "admin:login:lock:" + loginKeyPart(clientIP) + ":" + loginKeyPart(username)
func loginLockKey(tenantID uint64, username string, clientIP string) string {
return scopedAuthKey(tenantID, "admin:login:lock:"+loginKeyPart(clientIP)+":"+loginKeyPart(username))
}
func scopedAuthKey(tenantID uint64, base string) string {
if tenantID == 0 {
return base
}
return fmt.Sprintf("tenant:%d:%s", tenantID, base)
}
func adminPermissionCacheKey(ctx context.Context, adminID uint64) string {
key := fmt.Sprintf("admin:perms:%d", adminID)
if scope := tenancy.ScopeKey(ctx); scope != "" {
key += ":" + scope
}
return key
}
func (r *Repository) adminHasTenantAccess(ctx context.Context, adminID uint64) (bool, error) {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 {
return true, nil
}
var count int64
err := r.db.WithContext(ctx).Table("admin_user_roles AS aur").
Joins("JOIN roles AS r ON r.id = aur.role_id").
Where("aur.admin_user_id = ? AND (aur.tenant_id = ? OR r.code = ?)", adminID, tenantID, "super_admin").
Count(&count).Error
return count > 0, err
}
func loginKeyPart(value string) string {
@@ -6,6 +6,7 @@ import (
"strings"
"hfb_sys/backend/internal/modules/auth"
"hfb_sys/backend/internal/tenancy"
)
var (
@@ -100,6 +101,10 @@ func (s *Service) Refresh(ctx context.Context, refreshToken string) (*auth.Token
if err != nil {
return nil, newTokenValidationError(auth.TokenFailureReason(err), ErrInvalidRefreshToken)
}
tenantID := tenancy.IDFromContext(ctx)
if claims.TenantID > 0 && claims.TenantID != tenantID {
return nil, newTokenValidationError("tenant_mismatch", ErrInvalidRefreshToken)
}
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
@@ -113,7 +118,7 @@ func (s *Service) Refresh(ctx context.Context, refreshToken string) (*auth.Token
}
return nil, invalidRefreshTokenError(err)
}
pair, err := s.jwt.GenerateSubjectPairWithVersion(admin.ID, admin.Username, "admin", admin.TokenVersion)
pair, err := s.jwt.GenerateTenantPairWithVersion(admin.ID, admin.Username, "admin", admin.TokenVersion, tenantID)
if err != nil {
return nil, err
}
@@ -0,0 +1,85 @@
package adminauth
import (
"context"
"errors"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func adminTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func TestAdminAccessAndPermissionsAreScopedByTenant(t *testing.T) {
db := database.NewTestDB()
roles := []model.Role{
{Code: "super_admin", Name: "超级管理员"},
{Code: "cs", Name: "客服"},
{Code: "ops", Name: "运营"},
}
if err := db.Create(&roles).Error; err != nil {
t.Fatal(err)
}
permission := model.Permission{Code: "qa:view", Name: "查看质检", Resource: "qa", Action: "view"}
if err := db.Create(&permission).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.RolePermission{RoleID: roles[1].ID, PermissionID: permission.ID}).Error; err != nil {
t.Fatal(err)
}
tenantAdmin := model.AdminUser{Username: "tenant-cs", PasswordHash: "x", Status: "active", TokenVersion: 1}
otherAdmin := model.AdminUser{Username: "other-ops", PasswordHash: "x", Status: "active", TokenVersion: 1}
superAdmin := model.AdminUser{Username: "root", PasswordHash: "x", Status: "active", TokenVersion: 1}
if err := db.Create(&tenantAdmin).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&otherAdmin).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&superAdmin).Error; err != nil {
t.Fatal(err)
}
for _, assignment := range []model.AdminUserRole{
{AdminID: tenantAdmin.ID, RoleID: roles[1].ID, TenantID: 101},
{AdminID: otherAdmin.ID, RoleID: roles[2].ID, TenantID: 202},
{AdminID: superAdmin.ID, RoleID: roles[0].ID, TenantID: 0},
} {
if err := db.Create(&assignment).Error; err != nil {
t.Fatal(err)
}
}
repo := NewRepository(db, nil, nil)
if _, err := repo.FindActiveForToken(adminTenantContext(101), tenantAdmin.ID, 1); err != nil {
t.Fatalf("tenant admin token in own tenant: %v", err)
}
if _, err := repo.FindActiveForToken(adminTenantContext(202), tenantAdmin.ID, 1); !errors.Is(err, ErrAdminNotFound) {
t.Fatalf("tenant admin token in other tenant error = %v, want ErrAdminNotFound", err)
}
tenantDTO, err := repo.FindByID(adminTenantContext(101), tenantAdmin.ID)
if err != nil {
t.Fatal(err)
}
if tenantDTO.TenantID != 101 || len(tenantDTO.Roles) != 1 || tenantDTO.Roles[0].Code != "cs" {
t.Fatalf("tenant admin roles = %+v", tenantDTO)
}
if len(tenantDTO.Permissions) != 1 || tenantDTO.Permissions[0] != "qa:view" {
t.Fatalf("tenant admin permissions = %+v", tenantDTO.Permissions)
}
for _, tenantID := range []uint64{101, 202} {
superDTO, err := repo.FindByID(adminTenantContext(tenantID), superAdmin.ID)
if err != nil {
t.Fatalf("load super admin in tenant %d: %v", tenantID, err)
}
if len(superDTO.Permissions) != 1 || superDTO.Permissions[0] != "*" {
t.Fatalf("super admin permissions in tenant %d = %+v", tenantID, superDTO.Permissions)
}
}
}
+154 -21
View File
@@ -9,6 +9,7 @@ import (
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/adminrole"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"golang.org/x/crypto/bcrypt"
@@ -26,7 +27,7 @@ func NewRepository(db *gorm.DB, redis *redis.Client) *Repository {
}
func (r *Repository) List(ctx context.Context, page, pageSize int) (*PaginatedResult, error) {
db := r.db.WithContext(ctx)
db := r.scopedAdminQuery(ctx)
var total int64
if err := db.Model(&model.AdminUser{}).Count(&total).Error; err != nil {
return nil, err
@@ -55,7 +56,7 @@ func (r *Repository) List(ctx context.Context, page, pageSize int) (*PaginatedRe
func (r *Repository) FindByID(ctx context.Context, id uint64) (*AdminUserDTO, error) {
var admin model.AdminUser
if err := r.db.WithContext(ctx).First(&admin, id).Error; err != nil {
if err := r.scopedAdminQuery(ctx).Where("admin_users.id = ?", id).First(&admin).Error; err != nil {
return nil, err
}
roles, _ := r.getAdminRoles(ctx, admin.ID)
@@ -89,13 +90,22 @@ func (r *Repository) Create(ctx context.Context, req CreateAdminRequest) (*Admin
if err := r.db.WithContext(ctx).Create(&admin).Error; err != nil {
return nil, err
}
return r.FindByID(ctx, admin.ID)
return &AdminUserDTO{
ID: admin.ID,
Username: admin.Username,
Nickname: admin.Nickname,
Status: admin.Status,
Roles: []adminrole.RoleDTO{},
LastLoginAt: admin.LastLoginAt,
CreatedAt: admin.CreatedAt,
UpdatedAt: admin.UpdatedAt,
}, nil
}
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateAdminRequest) (*AdminUserDTO, error) {
db := r.db.WithContext(ctx)
var admin model.AdminUser
if err := db.First(&admin, id).Error; err != nil {
if err := r.scopedAdminQuery(ctx).Where("admin_users.id = ?", id).First(&admin).Error; err != nil {
return nil, err
}
if req.Nickname != "" {
@@ -122,9 +132,43 @@ func (r *Repository) Delete(ctx context.Context, id uint64, currentAdminID uint6
}
db := r.db.WithContext(ctx)
var admin model.AdminUser
if err := db.First(&admin, id).Error; err != nil {
if err := r.scopedAdminQuery(ctx).Where("admin_users.id = ?", id).First(&admin).Error; err != nil {
return err
}
tenantID := tenancy.IDFromContext(ctx)
if tenantID > 0 {
isSuper, err := r.adminHasRoleCode(ctx, id, "super_admin")
if err != nil {
return err
}
if isSuper {
return ErrLastSuperAdmin
}
err = db.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("admin_user_id = ? AND tenant_id = ?", id, tenantID).
Delete(&model.AdminUserRole{}).Error; err != nil {
return err
}
var remaining int64
if err := tx.Model(&model.AdminUserRole{}).
Where("admin_user_id = ?", id).Count(&remaining).Error; err != nil {
return err
}
if remaining == 0 {
if err := tx.Delete(&model.AdminUser{}, id).Error; err != nil {
return err
}
} else if err := r.bumpTokenVersion(tx, ctx, id, "tenant_roles_removed"); err != nil {
return err
}
return nil
})
if err != nil {
return err
}
r.invalidatePermCache(ctx, id)
return nil
}
// 检查是否是最后一个 super_admin
isLastSuper, err := r.isLastSuperAdmin(ctx, id)
if err != nil {
@@ -133,30 +177,42 @@ func (r *Repository) Delete(ctx context.Context, id uint64, currentAdminID uint6
if isLastSuper {
return ErrLastSuperAdmin
}
return db.Transaction(func(tx *gorm.DB) error {
err = db.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("admin_user_id = ?", id).Delete(&model.AdminUserRole{}).Error; err != nil {
return err
}
if err := tx.Delete(&model.AdminUser{}, id).Error; err != nil {
return err
}
r.invalidatePermCache(ctx, id)
return nil
})
if err == nil {
r.invalidatePermCache(ctx, id)
}
return err
}
func (r *Repository) AssignRoles(ctx context.Context, adminID uint64, roleIDs []uint64) error {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
var admin model.AdminUser
if err := db.First(&admin, adminID).Error; err != nil {
return err
}
err := db.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("admin_user_id = ?", adminID).Delete(&model.AdminUserRole{}).Error; err != nil {
roleIDs, err := r.validateTenantRoleIDs(ctx, roleIDs)
if err != nil {
return err
}
err = db.Transaction(func(tx *gorm.DB) error {
deleteQuery := tx.Where("admin_user_id = ?", adminID)
if tenantID > 0 {
deleteQuery = deleteQuery.Where("tenant_id = ?", tenantID)
}
if err := deleteQuery.Delete(&model.AdminUserRole{}).Error; err != nil {
return err
}
for _, rid := range roleIDs {
aur := model.AdminUserRole{AdminID: adminID, RoleID: rid}
aur := model.AdminUserRole{AdminID: adminID, RoleID: rid, TenantID: tenantID}
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&aur).Error; err != nil {
return err
}
@@ -195,7 +251,7 @@ func (r *Repository) ChangeOwnPassword(ctx context.Context, id uint64, oldPwd, n
func (r *Repository) ResetPassword(ctx context.Context, id uint64, newPwd string) error {
var admin model.AdminUser
if err := r.db.WithContext(ctx).First(&admin, id).Error; err != nil {
if err := r.scopedAdminQuery(ctx).Where("admin_users.id = ?", id).First(&admin).Error; err != nil {
return err
}
hash, err := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
@@ -215,22 +271,35 @@ func (r *Repository) ResetPassword(ctx context.Context, id uint64, newPwd string
}
func (r *Repository) GetPermissionCodes(ctx context.Context, adminID uint64) ([]string, error) {
isSuper, err := r.adminHasRoleCode(ctx, adminID, "super_admin")
if err != nil {
return nil, err
}
if isSuper {
return []string{"*"}, nil
}
var codes []string
err := r.db.WithContext(ctx).Table("admin_user_roles aur").
query := r.db.WithContext(ctx).Table("admin_user_roles aur").
Select("DISTINCT p.code").
Joins("JOIN role_permissions rp ON rp.role_id = aur.role_id").
Joins("JOIN permissions p ON p.id = rp.permission_id").
Where("aur.admin_user_id = ?", adminID).
Pluck("code", &codes).Error
Where("aur.admin_user_id = ?", adminID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("aur.tenant_id = ?", tenantID)
}
err = query.Pluck("code", &codes).Error
return codes, err
}
func (r *Repository) getAdminRoles(ctx context.Context, adminID uint64) ([]adminrole.RoleDTO, error) {
var roles []model.Role
err := r.db.WithContext(ctx).Table("roles").
query := r.db.WithContext(ctx).Table("roles").
Joins("JOIN admin_user_roles aur ON aur.role_id = roles.id").
Where("aur.admin_user_id = ?", adminID).
Find(&roles).Error
Where("aur.admin_user_id = ?", adminID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("(aur.tenant_id = ? OR roles.code = ?)", tenantID, "super_admin")
}
err := query.Find(&roles).Error
if err != nil {
return nil, err
}
@@ -260,7 +329,26 @@ func (r *Repository) invalidatePermCache(ctx context.Context, adminID uint64) {
if r.redis == nil {
return
}
r.redis.Del(ctx, permCacheKey(adminID))
patterns := []string{
permCacheKey(adminID),
fmt.Sprintf("admin:perms:%d:*", adminID),
}
for _, pattern := range patterns {
var cursor uint64
for {
keys, next, err := r.redis.Scan(ctx, cursor, pattern, 100).Result()
if err != nil {
return
}
if len(keys) > 0 {
_ = r.redis.Del(ctx, keys...).Err()
}
cursor = next
if cursor == 0 {
break
}
}
}
}
func (r *Repository) bumpTokenVersion(db *gorm.DB, ctx context.Context, adminID uint64, reason string) error {
@@ -288,10 +376,55 @@ func permCacheKey(adminID uint64) string {
return fmt.Sprintf("admin:perms:%d", adminID)
}
func (r *Repository) scopedAdminQuery(ctx context.Context) *gorm.DB {
query := r.db.WithContext(ctx).Model(&model.AdminUser{})
tenantID := tenancy.IDFromContext(ctx)
if tenantID > 0 {
query = query.Where(`EXISTS (
SELECT 1 FROM admin_user_roles aur
JOIN roles r ON r.id = aur.role_id
WHERE aur.admin_user_id = admin_users.id
AND (aur.tenant_id = ? OR r.code = ?)
)`, tenantID, "super_admin")
}
return query
}
func (r *Repository) validateTenantRoleIDs(ctx context.Context, roleIDs []uint64) ([]uint64, error) {
tenantID := tenancy.IDFromContext(ctx)
if tenantID == 0 || len(roleIDs) == 0 {
return roleIDs, nil
}
var count int64
if err := r.db.WithContext(ctx).Model(&model.Role{}).
Where("id IN ? AND code <> ?", roleIDs, "super_admin").
Count(&count).Error; err != nil {
return nil, err
}
unique := make(map[uint64]struct{}, len(roleIDs))
for _, id := range roleIDs {
unique[id] = struct{}{}
}
if count != int64(len(unique)) {
return nil, ErrRoleOutsideTenant
}
return roleIDs, nil
}
func (r *Repository) adminHasRoleCode(ctx context.Context, adminID uint64, code string) (bool, error) {
var count int64
err := r.db.WithContext(ctx).Table("admin_user_roles AS aur").
Joins("JOIN roles AS r ON r.id = aur.role_id").
Where("aur.admin_user_id = ? AND r.code = ?", adminID, code).
Count(&count).Error
return count > 0, err
}
var (
ErrCannotDeleteSelf = errors.New("cannot delete self")
ErrLastSuperAdmin = errors.New("cannot delete the last super admin")
ErrWrongPassword = errors.New("wrong password")
ErrCannotDeleteSelf = errors.New("cannot delete self")
ErrLastSuperAdmin = errors.New("cannot delete the last super admin")
ErrWrongPassword = errors.New("wrong password")
ErrRoleOutsideTenant = errors.New("role is not available in current tenant")
)
func IsNotFound(err error) bool {
@@ -0,0 +1,74 @@
package adminmgr
import (
"context"
"errors"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func adminMgrTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func TestAdminListIsScopedByTenantAndKeepsPlatformSuperAdmin(t *testing.T) {
db := database.NewTestDB()
roles := []model.Role{
{Code: "super_admin", Name: "超级管理员"},
{Code: "cs", Name: "客服"},
{Code: "ops", Name: "运营"},
}
if err := db.Create(&roles).Error; err != nil {
t.Fatal(err)
}
admins := []model.AdminUser{
{Username: "dachui-cs", PasswordHash: "x", Status: "active", TokenVersion: 1},
{Username: "jieyou-ops", PasswordHash: "x", Status: "active", TokenVersion: 1},
{Username: "root", PasswordHash: "x", Status: "active", TokenVersion: 1},
}
if err := db.Create(&admins).Error; err != nil {
t.Fatal(err)
}
for _, assignment := range []model.AdminUserRole{
{AdminID: admins[0].ID, RoleID: roles[1].ID, TenantID: 101},
{AdminID: admins[1].ID, RoleID: roles[2].ID, TenantID: 202},
{AdminID: admins[2].ID, RoleID: roles[0].ID, TenantID: 0},
} {
if err := db.Create(&assignment).Error; err != nil {
t.Fatal(err)
}
}
repo := NewRepository(db, nil)
result, err := repo.List(adminMgrTenantContext(101), 1, 20)
if err != nil {
t.Fatalf("list tenant admins: %v", err)
}
if result.Total != 2 || len(result.Items) != 2 {
t.Fatalf("dachui admin list = %+v", result)
}
if result.Items[0].ID != admins[2].ID || result.Items[1].ID != admins[0].ID {
t.Fatalf("dachui admin ids = %d,%d", result.Items[0].ID, result.Items[1].ID)
}
if result.Items[1].Roles[0].Code != "cs" {
t.Fatalf("dachui role = %+v", result.Items[1].Roles)
}
if err := repo.AssignRoles(adminMgrTenantContext(101), admins[1].ID, []uint64{roles[2].ID}); err != nil {
t.Fatalf("assign jieyou admin to dachui: %v", err)
}
result, err = repo.List(adminMgrTenantContext(101), 1, 20)
if err != nil {
t.Fatal(err)
}
if result.Total != 3 {
t.Fatalf("shared admin visibility total = %d, want 3", result.Total)
}
if err := repo.AssignRoles(adminMgrTenantContext(101), admins[1].ID, []uint64{roles[0].ID}); !errors.Is(err, ErrRoleOutsideTenant) {
t.Fatalf("assign platform super role in tenant error = %v", err)
}
}
@@ -126,6 +126,8 @@ func writeError(c *gin.Context, err error) {
response.ServiceUnavailable(c, "数据库未连接")
case errors.Is(err, ErrProtectedRole):
response.BadRequest(c, "该角色为系统内置角色,不可删除")
case errors.Is(err, ErrPlatformAdminRequired):
response.Error(c, http.StatusForbidden, "forbidden", "仅平台超级管理员可以修改全局角色")
case IsNotFound(err):
response.Error(c, http.StatusNotFound, "not_found", "角色不存在")
default:
@@ -8,6 +8,7 @@ import (
"hfb_sys/backend/internal/auditlog"
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
@@ -79,6 +80,9 @@ func (r *Repository) FindByID(ctx context.Context, id uint64) (*RoleDTO, error)
}
func (r *Repository) Create(ctx context.Context, req CreateRoleRequest) (*RoleDTO, error) {
if err := r.requirePlatformSuperAdmin(ctx); err != nil {
return nil, err
}
role := model.Role{
Code: req.Code,
Name: req.Name,
@@ -91,6 +95,9 @@ func (r *Repository) Create(ctx context.Context, req CreateRoleRequest) (*RoleDT
}
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateRoleRequest) (*RoleDTO, error) {
if err := r.requirePlatformSuperAdmin(ctx); err != nil {
return nil, err
}
db := r.db.WithContext(ctx)
var role model.Role
if err := db.First(&role, id).Error; err != nil {
@@ -105,6 +112,9 @@ func (r *Repository) Update(ctx context.Context, id uint64, req UpdateRoleReques
}
func (r *Repository) Delete(ctx context.Context, id uint64) error {
if err := r.requirePlatformSuperAdmin(ctx); err != nil {
return err
}
db := r.db.WithContext(ctx)
var role model.Role
if err := db.First(&role, id).Error; err != nil {
@@ -137,6 +147,9 @@ func (r *Repository) Delete(ctx context.Context, id uint64) error {
}
func (r *Repository) AssignPermissions(ctx context.Context, roleID uint64, permIDs []uint64) error {
if err := r.requirePlatformSuperAdmin(ctx); err != nil {
return err
}
db := r.db.WithContext(ctx)
var role model.Role
if err := db.First(&role, roleID).Error; err != nil {
@@ -253,14 +266,55 @@ func (r *Repository) invalidateAdminPermCaches(ctx context.Context, adminIDs []u
if r.redis == nil || len(adminIDs) == 0 {
return
}
keys := make([]string, 0, len(adminIDs))
for _, id := range adminIDs {
keys = append(keys, fmt.Sprintf("admin:perms:%d", id))
patterns := []string{
fmt.Sprintf("admin:perms:%d", id),
fmt.Sprintf("admin:perms:%d:*", id),
}
for _, pattern := range patterns {
var cursor uint64
for {
keys, next, err := r.redis.Scan(ctx, cursor, pattern, 100).Result()
if err != nil {
return
}
if len(keys) > 0 {
_ = r.redis.Del(ctx, keys...).Err()
}
cursor = next
if cursor == 0 {
break
}
}
}
}
_ = r.redis.Del(ctx, keys...).Err()
}
var ErrProtectedRole = errors.New("protected role")
func (r *Repository) requirePlatformSuperAdmin(ctx context.Context) error {
if tenancy.IDFromContext(ctx) == 0 {
return nil
}
adminID := logging.AdminIDFromContext(ctx)
if adminID == 0 {
return ErrPlatformAdminRequired
}
var count int64
if err := r.db.WithContext(ctx).Table("admin_user_roles AS aur").
Joins("JOIN roles AS r ON r.id = aur.role_id").
Where("aur.admin_user_id = ? AND r.code = ?", adminID, "super_admin").
Count(&count).Error; err != nil {
return err
}
if count == 0 {
return ErrPlatformAdminRequired
}
return nil
}
var (
ErrProtectedRole = errors.New("protected role")
ErrPlatformAdminRequired = errors.New("platform super admin required")
)
func IsNotFound(err error) bool {
return errors.Is(err, gorm.ErrRecordNotFound)
+19 -3
View File
@@ -55,6 +55,8 @@ type Claims struct {
TokenType string `json:"typ"`
SubjectType string `json:"sub_type"`
TokenVersion int64 `json:"ver,omitempty"`
TenantID uint64 `json:"tid,omitempty"`
Scope string `json:"scope,omitempty"`
jwt.RegisteredClaims
}
@@ -83,11 +85,23 @@ func (m *JWTManager) GenerateSubjectPair(userID uint64, subject string, subjectT
}
func (m *JWTManager) GenerateSubjectPairWithVersion(userID uint64, subject string, subjectType string, tokenVersion int64) (TokenPair, error) {
accessToken, err := m.generate(userID, subject, subjectType, tokenTypeAccess, tokenVersion, m.accessTTL)
return m.GenerateScopedSubjectPairWithVersion(userID, subject, subjectType, tokenVersion, 0, "legacy")
}
func (m *JWTManager) GenerateTenantPairWithVersion(userID uint64, subject string, subjectType string, tokenVersion int64, tenantID uint64) (TokenPair, error) {
scope := "tenant"
if tenantID == 0 {
scope = "platform"
}
return m.GenerateScopedSubjectPairWithVersion(userID, subject, subjectType, tokenVersion, tenantID, scope)
}
func (m *JWTManager) GenerateScopedSubjectPairWithVersion(userID uint64, subject string, subjectType string, tokenVersion int64, tenantID uint64, scope string) (TokenPair, error) {
accessToken, err := m.generate(userID, subject, subjectType, tokenTypeAccess, tokenVersion, tenantID, scope, m.accessTTL)
if err != nil {
return TokenPair{}, err
}
refreshToken, err := m.generate(userID, subject, subjectType, tokenTypeRefresh, tokenVersion, m.refreshTTL)
refreshToken, err := m.generate(userID, subject, subjectType, tokenTypeRefresh, tokenVersion, tenantID, scope, m.refreshTTL)
if err != nil {
return TokenPair{}, err
}
@@ -145,7 +159,7 @@ func jwtFailureReason(err error) string {
}
}
func (m *JWTManager) generate(userID uint64, subject string, subjectType string, tokenType string, tokenVersion int64, ttl time.Duration) (string, error) {
func (m *JWTManager) generate(userID uint64, subject string, subjectType string, tokenType string, tokenVersion int64, tenantID uint64, scope string, ttl time.Duration) (string, error) {
now := time.Now()
claims := Claims{
UserID: userID,
@@ -153,6 +167,8 @@ func (m *JWTManager) generate(userID uint64, subject string, subjectType string,
TokenType: tokenType,
SubjectType: subjectType,
TokenVersion: tokenVersion,
TenantID: tenantID,
Scope: scope,
RegisteredClaims: jwt.RegisteredClaims{
Subject: subject,
IssuedAt: jwt.NewNumericDate(now),
+48 -11
View File
@@ -8,6 +8,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -33,7 +34,11 @@ func NewUserRepository(db *gorm.DB) *UserRepository {
func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User, error) {
var user model.User
if err := r.db.WithContext(ctx).First(&user, id).Error; err != nil {
query := r.db.WithContext(ctx)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&user, id).Error; err != nil {
return nil, err
}
return &user, nil
@@ -45,7 +50,11 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke
return nil, ErrDependencyUnavailable
}
var user model.User
if err := r.db.WithContext(ctx).
query := r.db.WithContext(ctx)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.
Select("id, phone, status, token_version").
First(&user, id).Error; err != nil {
return nil, err
@@ -60,7 +69,11 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke
}
func (r *UserRepository) UpdateProfile(ctx context.Context, id uint64, nickname string, avatarURL string) (*model.User, error) {
if err := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", id).Updates(map[string]any{
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Updates(map[string]any{
"nickname": nickname,
"avatar_url": avatarURL,
}).Error; err != nil {
@@ -84,11 +97,13 @@ func (r *UserRepository) resolveSiteID(ctx context.Context, siteCode string) uin
func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string, trackCode string, siteCode ...string) (*model.User, error) {
now := time.Now()
code := sanitizeTrackCode(trackCode)
tenantID := tenancy.IDFromContext(ctx)
var siteID uint64
if len(siteCode) > 0 {
siteID = r.resolveSiteID(ctx, siteCode[0])
}
user := model.User{
TenantID: tenantID,
Phone: phone,
Nickname: "用户" + phone[len(phone)-4:],
RealnameStatus: "unverified",
@@ -100,16 +115,25 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
LastLoginAt: &now,
}
err := r.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "phone"}},
onConflict := clause.OnConflict{
DoUpdates: clause.AssignmentColumns([]string{"last_login_at", "updated_at"}),
}).Create(&user).Error
}
if tenantID > 0 {
onConflict.Columns = []clause.Column{{Name: "tenant_id"}, {Name: "phone"}}
} else {
onConflict.Columns = []clause.Column{{Name: "phone"}}
}
err := r.db.WithContext(ctx).Clauses(onConflict).Create(&user).Error
if err != nil {
return nil, err
}
var found model.User
if err := r.db.WithContext(ctx).Where("phone = ?", phone).First(&found).Error; err != nil {
query := r.db.WithContext(ctx).Where("phone = ?", phone)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&found).Error; err != nil {
return nil, err
}
return &found, nil
@@ -117,14 +141,22 @@ func (r *UserRepository) FindOrCreateByPhone(ctx context.Context, phone string,
func (r *UserRepository) FindByPhone(ctx context.Context, phone string) (*model.User, error) {
var user model.User
if err := r.db.WithContext(ctx).Where("phone = ?", phone).First(&user).Error; err != nil {
query := r.db.WithContext(ctx).Where("phone = ?", phone)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&user).Error; err != nil {
return nil, err
}
return &user, nil
}
func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash string) error {
return r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID).Updates(map[string]any{
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.Updates(map[string]any{
"password_hash": hash,
"token_version": gorm.Expr("token_version + 1"),
}).Error
@@ -132,18 +164,23 @@ func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash st
// RevokeTokens 使当前用户的所有 access/refresh token 立即失效。
func (r *UserRepository) RevokeTokens(ctx context.Context, userID uint64) error {
return r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID).
UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error
query := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error
}
func (r *UserRepository) RegisterWithPassword(ctx context.Context, phone string, hash string, trackCode string, siteCode ...string) (*model.User, error) {
now := time.Now()
code := sanitizeTrackCode(trackCode)
tenantID := tenancy.IDFromContext(ctx)
var siteID uint64
if len(siteCode) > 0 {
siteID = r.resolveSiteID(ctx, siteCode[0])
}
user := model.User{
TenantID: tenantID,
Phone: phone,
PasswordHash: hash,
Nickname: "用户" + phone[len(phone)-4:],
+56 -27
View File
@@ -14,6 +14,7 @@ import (
smsprovider "hfb_sys/backend/internal/integrations/sms"
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
@@ -94,8 +95,9 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string, captchaID strin
if !isPhone(phone) {
return ErrInvalidPhone
}
tenantID := tenancy.IDFromContext(ctx)
cooldownKey := "sms:cooldown:login:" + phone
cooldownKey := smsCooldownKey(tenantID, phone)
exists, err := s.redis.Exists(ctx, cooldownKey).Result()
if err != nil {
return err
@@ -104,7 +106,7 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string, captchaID strin
return ErrCodeRateLimited
}
hourlyKey := "sms:hourly:login:" + phone
hourlyKey := smsHourlyKey(tenantID, phone)
hourlyCount, err := s.redis.Get(ctx, hourlyKey).Int()
if err != nil && !errors.Is(err, redis.Nil) {
return err
@@ -181,12 +183,12 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string, captchaID strin
}
pipe := s.redis.TxPipeline()
pipe.Set(ctx, codeKey(phone), code, 5*time.Minute)
pipe.Set(ctx, codeKey(tenantID, phone), code, 5*time.Minute)
pipe.Set(ctx, cooldownKey, "1", smsLoginCooldown)
pipe.Incr(ctx, hourlyKey)
pipe.Expire(ctx, hourlyKey, smsLoginHourlyWindow)
pipe.Incr(ctx, "sms:daily:login:"+phone)
pipe.Expire(ctx, "sms:daily:login:"+phone, 24*time.Hour)
pipe.Incr(ctx, smsDailyKey(tenantID, phone))
pipe.Expire(ctx, smsDailyKey(tenantID, phone), 24*time.Hour)
if _, err := pipe.Exec(ctx); err != nil {
return err
}
@@ -200,8 +202,9 @@ func (s *Service) LoginWithSMS(ctx context.Context, phone string, code string, t
if !isPhone(phone) {
return LoginResult{}, ErrInvalidPhone
}
tenantID := tenancy.IDFromContext(ctx)
stored, err := s.redis.Get(ctx, codeKey(phone)).Result()
stored, err := s.redis.Get(ctx, codeKey(tenantID, phone)).Result()
if errors.Is(err, redis.Nil) || stored != code {
return LoginResult{}, ErrCodeInvalid
}
@@ -221,7 +224,7 @@ func (s *Service) LoginWithSMS(ctx context.Context, phone string, code string, t
if err != nil {
return LoginResult{}, err
}
_ = s.redis.Del(ctx, codeKey(phone)).Err()
_ = s.redis.Del(ctx, codeKey(tenantID, phone)).Err()
return LoginResult{User: user, Tokens: tokens}, nil
}
@@ -234,6 +237,10 @@ func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (TokenP
if err != nil {
return TokenPair{}, err
}
tenantID := tenancy.IDFromContext(ctx)
if claims.TenantID > 0 && claims.TenantID != tenantID {
return TokenPair{}, ErrTokenVersionMismatch
}
user, err := s.users.FindActiveForToken(ctx, claims.UserID, claims.TokenVersion)
if err != nil {
return TokenPair{}, err
@@ -245,7 +252,7 @@ func (s *Service) generateUserTokenPair(user *model.User) (TokenPair, error) {
if s.jwt == nil {
return TokenPair{}, ErrDependencyUnavailable
}
return s.jwt.GenerateSubjectPairWithVersion(user.ID, user.Phone, "user", user.TokenVersion)
return s.jwt.GenerateTenantPairWithVersion(user.ID, user.Phone, "user", user.TokenVersion, user.TenantID)
}
func (s *Service) Logout(ctx context.Context, userID uint64) error {
@@ -255,8 +262,27 @@ func (s *Service) Logout(ctx context.Context, userID uint64) error {
return s.users.RevokeTokens(ctx, userID)
}
func codeKey(phone string) string {
return "sms:code:login:" + phone
func codeKey(tenantID uint64, phone string) string {
return tenantKey("sms:code:login:"+phone, tenantID)
}
func smsCooldownKey(tenantID uint64, phone string) string {
return tenantKey("sms:cooldown:login:"+phone, tenantID)
}
func smsHourlyKey(tenantID uint64, phone string) string {
return tenantKey("sms:hourly:login:"+phone, tenantID)
}
func smsDailyKey(tenantID uint64, phone string) string {
return tenantKey("sms:daily:login:"+phone, tenantID)
}
func tenantKey(base string, tenantID uint64) string {
if tenantID == 0 {
return base
}
return fmt.Sprintf("tenant:%d:%s", tenantID, base)
}
func isPhone(phone string) bool {
@@ -289,8 +315,9 @@ func (s *Service) LoginWithPassword(ctx context.Context, phone, password, client
if !isPhone(phone) {
return LoginResult{}, ErrInvalidPhone
}
tenantID := tenancy.IDFromContext(ctx)
locked, err := s.redis.Exists(ctx, loginLockRedisKey(phone, clientIP)).Result()
locked, err := s.redis.Exists(ctx, loginLockRedisKey(tenantID, phone, clientIP)).Result()
if err != nil {
return LoginResult{}, err
}
@@ -301,7 +328,7 @@ func (s *Service) LoginWithPassword(ctx context.Context, phone, password, client
user, err := s.users.FindByPhone(ctx, phone)
if IsNotFound(err) {
// 用户不存在也计失败次数,避免该接口被用于探测手机号是否已注册
_ = recordLoginFailure(ctx, s.redis, phone, clientIP)
_ = recordLoginFailure(ctx, s.redis, tenantID, phone, clientIP)
return LoginResult{}, ErrInvalidPassword
}
if err != nil {
@@ -312,7 +339,7 @@ func (s *Service) LoginWithPassword(ctx context.Context, phone, password, client
return LoginResult{}, ErrPasswordNotSet
}
if checkPasswordHash(password, user.PasswordHash) != nil {
_ = recordLoginFailure(ctx, s.redis, phone, clientIP)
_ = recordLoginFailure(ctx, s.redis, tenantID, phone, clientIP)
return LoginResult{}, ErrInvalidPassword
}
@@ -320,7 +347,7 @@ func (s *Service) LoginWithPassword(ctx context.Context, phone, password, client
return LoginResult{}, ErrUserDisabled
}
_ = clearLoginFailure(ctx, s.redis, phone, clientIP)
_ = clearLoginFailure(ctx, s.redis, tenantID, phone, clientIP)
tokens, err := s.generateUserTokenPair(user)
if err != nil {
@@ -357,8 +384,9 @@ func (s *Service) ResetPassword(ctx context.Context, phone, code, newPassword st
if !isPhone(phone) {
return ErrInvalidPhone
}
tenantID := tenancy.IDFromContext(ctx)
stored, err := s.redis.Get(ctx, codeKey(phone)).Result()
stored, err := s.redis.Get(ctx, codeKey(tenantID, phone)).Result()
if errors.Is(err, redis.Nil) || stored != code {
return ErrCodeInvalid
}
@@ -381,7 +409,7 @@ func (s *Service) ResetPassword(ctx context.Context, phone, code, newPassword st
if err := s.users.SetPassword(ctx, user.ID, string(hash)); err != nil {
return err
}
_ = s.redis.Del(ctx, codeKey(phone)).Err()
_ = s.redis.Del(ctx, codeKey(tenantID, phone)).Err()
return nil
}
@@ -392,8 +420,9 @@ func (s *Service) RegisterWithPassword(ctx context.Context, phone, code, passwor
if !isPhone(phone) {
return LoginResult{}, ErrInvalidPhone
}
tenantID := tenancy.IDFromContext(ctx)
stored, err := s.redis.Get(ctx, codeKey(phone)).Result()
stored, err := s.redis.Get(ctx, codeKey(tenantID, phone)).Result()
if errors.Is(err, redis.Nil) || stored != code {
return LoginResult{}, ErrCodeInvalid
}
@@ -431,7 +460,7 @@ func (s *Service) RegisterWithPassword(ctx context.Context, phone, code, passwor
if err != nil {
return LoginResult{}, err
}
_ = s.redis.Del(ctx, codeKey(phone)).Err()
_ = s.redis.Del(ctx, codeKey(tenantID, phone)).Err()
return LoginResult{User: user, Tokens: tokens}, nil
}
@@ -443,27 +472,27 @@ func checkPasswordHash(password, hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
func recordLoginFailure(ctx context.Context, rdb *redis.Client, phone, clientIP string) error {
key := loginFailureRedisKey(phone, clientIP)
func recordLoginFailure(ctx context.Context, rdb *redis.Client, tenantID uint64, phone, clientIP string) error {
key := loginFailureRedisKey(tenantID, phone, clientIP)
count, err := rdb.Incr(ctx, key).Result()
if err != nil {
return err
}
_ = rdb.Expire(ctx, key, loginFailureTTL).Err()
if count >= int64(loginMaxFailureCount) {
_ = rdb.Set(ctx, loginLockRedisKey(phone, clientIP), "1", loginLockTTL).Err()
_ = rdb.Set(ctx, loginLockRedisKey(tenantID, phone, clientIP), "1", loginLockTTL).Err()
}
return nil
}
func clearLoginFailure(ctx context.Context, rdb *redis.Client, phone, clientIP string) error {
return rdb.Del(ctx, loginFailureRedisKey(phone, clientIP), loginLockRedisKey(phone, clientIP)).Err()
func clearLoginFailure(ctx context.Context, rdb *redis.Client, tenantID uint64, phone, clientIP string) error {
return rdb.Del(ctx, loginFailureRedisKey(tenantID, phone, clientIP), loginLockRedisKey(tenantID, phone, clientIP)).Err()
}
func loginFailureRedisKey(phone, clientIP string) string {
return fmt.Sprintf("user:login:fail:%s:%s", clientIP, phone)
func loginFailureRedisKey(tenantID uint64, phone, clientIP string) string {
return tenantKey(fmt.Sprintf("user:login:fail:%s:%s", clientIP, phone), tenantID)
}
func loginLockRedisKey(phone, clientIP string) string {
return fmt.Sprintf("user:login:lock:%s:%s", clientIP, phone)
func loginLockRedisKey(tenantID uint64, phone, clientIP string) string {
return tenantKey(fmt.Sprintf("user:login:lock:%s:%s", clientIP, phone), tenantID)
}
@@ -0,0 +1,87 @@
package auth
import (
"context"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func authTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func TestUserRepositoryScopesSamePhoneByTenant(t *testing.T) {
db := database.NewTestDB()
repo := NewUserRepository(db)
const phone = "13600000001"
dachuiCtx := authTenantContext(101)
jieyouCtx := authTenantContext(202)
dachuiUser, err := repo.RegisterWithPassword(dachuiCtx, phone, "hash-dachui", "")
if err != nil {
t.Fatalf("register dachui user: %v", err)
}
jieyouUser, err := repo.RegisterWithPassword(jieyouCtx, phone, "hash-jieyou", "")
if err != nil {
t.Fatalf("register jieyou user: %v", err)
}
if dachuiUser.ID == jieyouUser.ID || dachuiUser.TenantID != 101 || jieyouUser.TenantID != 202 {
t.Fatalf("tenant users = %+v / %+v", dachuiUser, jieyouUser)
}
foundDachui, err := repo.FindByPhone(dachuiCtx, phone)
if err != nil || foundDachui.PasswordHash != "hash-dachui" {
t.Fatalf("find dachui user = %+v, err=%v", foundDachui, err)
}
foundJieyou, err := repo.FindByPhone(jieyouCtx, phone)
if err != nil || foundJieyou.PasswordHash != "hash-jieyou" {
t.Fatalf("find jieyou user = %+v, err=%v", foundJieyou, err)
}
if _, err := repo.FindByID(dachuiCtx, jieyouUser.ID); err == nil {
t.Fatal("dachui context must not load jieyou user")
}
}
func TestTenantTokenClaimsAndRedisKeysAreIsolated(t *testing.T) {
manager := NewJWTManager("tenant-scope-test-secret")
pair, err := manager.GenerateTenantPairWithVersion(7, "13600000007", "user", 1, 101)
if err != nil {
t.Fatalf("generate tenant token: %v", err)
}
claims, err := manager.ParseSubject(pair.AccessToken, "access", "user")
if err != nil {
t.Fatalf("parse tenant token: %v", err)
}
if claims.TenantID != 101 || claims.Scope != "tenant" {
t.Fatalf("tenant claims = %+v", claims)
}
phone := "13600000007"
if codeKey(101, phone) == codeKey(202, phone) {
t.Fatal("sms code keys must differ by tenant")
}
if loginFailureRedisKey(101, phone, "127.0.0.1") == loginFailureRedisKey(202, phone, "127.0.0.1") {
t.Fatal("login failure keys must differ by tenant")
}
}
func TestTenantUsersRemainSeparateRows(t *testing.T) {
db := database.NewTestDB()
users := []model.User{
{TenantID: 101, Phone: "13600000002", Status: "active"},
{TenantID: 202, Phone: "13600000002", Status: "active"},
}
if err := db.Create(&users).Error; err != nil {
t.Fatalf("create same-phone tenant users: %v", err)
}
var count int64
if err := db.Model(&model.User{}).Where("phone = ?", "13600000002").Count(&count).Error; err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("same phone user count = %d, want 2", count)
}
}
@@ -13,6 +13,7 @@ import (
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/wallet"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -65,7 +66,11 @@ func (r *Repository) GenerateUniqueInviteCode(ctx context.Context) (string, erro
}
code := hex.EncodeToString(bytes)[:7] // 7 位如 0d76234
var count int64
if err := r.db.WithContext(ctx).Model(&model.User{}).Where("invite_code = ?", code).Count(&count).Error; err != nil {
query := r.db.WithContext(ctx).Model(&model.User{}).Where("invite_code = ?", code)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Count(&count).Error; err != nil {
return "", err
}
if count == 0 {
@@ -81,7 +86,11 @@ func (r *Repository) EnsureUserInviteCode(ctx context.Context, userID uint64) (s
return "", ErrDependencyUnavailable
}
var user model.User
if err := r.db.WithContext(ctx).First(&user, userID).Error; err != nil {
query := r.db.WithContext(ctx).Where("id = ?", userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&user).Error; err != nil {
return "", err
}
if user.InviteCode != nil && *user.InviteCode != "" {
@@ -106,7 +115,11 @@ func (r *Repository) OnUserRealnameVerified(ctx context.Context, userID uint64)
}
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var user model.User
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&user, userID).Error; err != nil {
userQuery := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
if err := userQuery.First(&user).Error; err != nil {
return err
}
now := time.Now()
@@ -120,7 +133,11 @@ func (r *Repository) OnUserRealnameVerified(ctx context.Context, userID uint64)
}
code := hex.EncodeToString(bytes)[:7]
var count int64
if err := tx.Model(&model.User{}).Where("invite_code = ?", code).Count(&count).Error; err != nil {
countQuery := tx.Model(&model.User{}).Where("invite_code = ?", code)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
countQuery = countQuery.Where("tenant_id = ?", tenantID)
}
if err := countQuery.Count(&count).Error; err != nil {
return err
}
if count == 0 {
@@ -162,7 +179,11 @@ func (r *Repository) GetInviteCodeInfo(ctx context.Context, code string) (*Invit
return &InviteCodeInfoDTO{Valid: false}, nil
}
var user model.User
if err := r.db.WithContext(ctx).Where("invite_code = ?", cleanCode).First(&user).Error; err != nil {
query := r.db.WithContext(ctx).Where("invite_code = ?", cleanCode)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return &InviteCodeInfoDTO{Valid: false, InviteCode: cleanCode}, nil
}
@@ -201,7 +222,11 @@ func (r *Repository) BindInvitation(ctx context.Context, inviteeID uint64, code
}
var inviter model.User
if err := tx.Where("invite_code = ?", cleanCode).First(&inviter).Error; err != nil {
inviterQuery := tx.Where("invite_code = ?", cleanCode)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
inviterQuery = inviterQuery.Where("tenant_id = ?", tenantID)
}
if err := inviterQuery.First(&inviter).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrInvalidInviteCode
}
@@ -223,7 +248,11 @@ func (r *Repository) BindInvitation(ctx context.Context, inviteeID uint64, code
}
var invitee model.User
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&invitee, inviteeID).Error; err != nil {
inviteeQuery := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", inviteeID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
inviteeQuery = inviteeQuery.Where("tenant_id = ?", tenantID)
}
if err := inviteeQuery.First(&invitee).Error; err != nil {
return err
}
@@ -8,6 +8,7 @@ import (
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/crypto"
"gorm.io/datatypes"
@@ -28,16 +29,22 @@ func NewRepository(db *gorm.DB, encryptor crypto.Encryptor) *Repository {
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
baseQuery := func() *gorm.DB {
query := db.Model(&model.UserPaymentAccount{}).Where("user_id = ? AND status = ?", userID, "active")
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query
}
var total int64
if err := db.Model(&model.UserPaymentAccount{}).
Where("user_id = ? AND status = ?", userID, "active").
Count(&total).Error; err != nil {
if err := baseQuery().Count(&total).Error; err != nil {
return nil, err
}
offset := (page - 1) * pageSize
var accounts []model.UserPaymentAccount
if err := db.Where("user_id = ? AND status = ?", userID, "active").
if err := baseQuery().
Order("is_default DESC, created_at DESC").
Offset(offset).Limit(pageSize).
Find(&accounts).Error; err != nil {
@@ -63,8 +70,8 @@ func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int
func (r *Repository) FindByID(ctx context.Context, userID, id uint64) (*PaymentAccountDTO, error) {
var account model.UserPaymentAccount
if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ? AND status = ?", id, userID, "active").
First(&account).Error; err != nil {
query := r.accountQuery(ctx, userID).Where("id = ?", id)
if err := query.First(&account).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAccountNotFound
}
@@ -75,6 +82,7 @@ func (r *Repository) FindByID(ctx context.Context, userID, id uint64) (*PaymentA
func (r *Repository) Create(ctx context.Context, userID uint64, req CreatePaymentAccountRequest) (*PaymentAccountDTO, error) {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
if err := r.validateCertificateURLs(ctx, userID, req.CertificateURLs, nil); err != nil {
return nil, err
}
@@ -93,12 +101,15 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreatePaymen
// 如果是第一个账号,自动设为默认
isDefault := false
var count int64
db.Model(&model.UserPaymentAccount{}).Where("user_id = ? AND status = ?", userID, "active").Count(&count)
if err := r.accountQuery(ctx, userID).Count(&count).Error; err != nil {
return nil, err
}
if count == 0 {
isDefault = true
}
account := model.UserPaymentAccount{
TenantID: tenantID,
UserID: userID,
AccountType: req.AccountType,
AccountName: req.AccountName,
@@ -119,8 +130,9 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreatePaymen
func (r *Repository) Update(ctx context.Context, userID, id uint64, req UpdatePaymentAccountRequest) (*PaymentAccountDTO, error) {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
var account model.UserPaymentAccount
if err := db.Where("id = ? AND user_id = ? AND status = ?", id, userID, "active").
if err := r.accountQuery(ctx, userID).Where("id = ?", id).
First(&account).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrAccountNotFound
@@ -146,9 +158,13 @@ func (r *Repository) Update(ctx context.Context, userID, id uint64, req UpdatePa
if req.IsDefault != nil && *req.IsDefault {
// 先取消其他默认账号
db.Model(&model.UserPaymentAccount{}).
Where("user_id = ? AND id != ?", userID, id).
Update("is_default", false)
query := db.Model(&model.UserPaymentAccount{}).Where("user_id = ? AND id != ?", userID, id)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Update("is_default", false).Error; err != nil {
return nil, err
}
updates["is_default"] = true
}
@@ -212,7 +228,7 @@ func paymentCertificateKey(value string) (string, bool) {
func (r *Repository) Delete(ctx context.Context, userID, id uint64) error {
db := r.db.WithContext(ctx)
var account model.UserPaymentAccount
if err := db.Where("id = ? AND user_id = ? AND status = ?", id, userID, "active").
if err := r.accountQuery(ctx, userID).Where("id = ?", id).
First(&account).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrAccountNotFound
@@ -227,7 +243,7 @@ func (r *Repository) Delete(ctx context.Context, userID, id uint64) error {
func (r *Repository) SetDefault(ctx context.Context, userID, id uint64) error {
// 验证账号存在
var account model.UserPaymentAccount
if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ? AND status = ?", id, userID, "active").
if err := r.accountQuery(ctx, userID).Where("id = ?", id).
First(&account).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrAccountNotFound
@@ -236,10 +252,14 @@ func (r *Repository) SetDefault(ctx context.Context, userID, id uint64) error {
}
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
tenantID := tenancy.IDFromContext(ctx)
// 取消其他默认账号
if err := tx.Model(&model.UserPaymentAccount{}).
Where("user_id = ? AND id != ?", userID, id).
Update("is_default", false).Error; err != nil {
query := tx.Model(&model.UserPaymentAccount{}).
Where("user_id = ? AND id != ?", userID, id)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Update("is_default", false).Error; err != nil {
return err
}
// 设置当前为默认
@@ -249,8 +269,7 @@ func (r *Repository) SetDefault(ctx context.Context, userID, id uint64) error {
func (r *Repository) CountByUser(ctx context.Context, userID uint64) (int64, error) {
var count int64
err := r.db.WithContext(ctx).Model(&model.UserPaymentAccount{}).
Where("user_id = ? AND status = ?", userID, "active").
err := r.accountQuery(ctx, userID).
Count(&count).Error
return count, err
}
@@ -258,7 +277,12 @@ func (r *Repository) CountByUser(ctx context.Context, userID uint64) (int64, err
func (r *Repository) ValidateRealname(ctx context.Context, userID uint64, accountName string) error {
var user model.User
db := r.db.WithContext(ctx)
if err := db.First(&user, userID).Error; err != nil {
tenantID := tenancy.IDFromContext(ctx)
userQuery := db.Where("id = ?", userID)
if tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
if err := userQuery.First(&user).Error; err != nil {
return err
}
@@ -268,7 +292,11 @@ func (r *Repository) ValidateRealname(ctx context.Context, userID uint64, accoun
// 获取实名信息
var realname model.UserRealname
if err := db.Where("user_id = ? AND status = ?", userID, "verified").
realnameQuery := db.Where("user_id = ? AND status = ?", userID, "verified")
if tenantID > 0 {
realnameQuery = realnameQuery.Where("tenant_id = ?", tenantID)
}
if err := realnameQuery.
First(&realname).Error; err != nil {
return ErrRealnameRequired
}
@@ -293,6 +321,15 @@ func (r *Repository) ValidateRealname(ctx context.Context, userID uint64, accoun
return nil
}
func (r *Repository) accountQuery(ctx context.Context, userID uint64) *gorm.DB {
query := r.db.WithContext(ctx).Model(&model.UserPaymentAccount{}).
Where("user_id = ? AND status = ?", userID, "active")
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query
}
// 使用脱敏姓名进行前缀匹配(兼容旧数据)
func (r *Repository) validateByMaskedName(maskedName, accountName string) error {
maskedName = strings.ReplaceAll(maskedName, " ", "")
@@ -0,0 +1,78 @@
package paymentaccount
import (
"context"
"errors"
"testing"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
func paymentTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func TestPaymentAccountsAreScopedByTenant(t *testing.T) {
db := database.NewTestDB()
dachuiUser := model.User{TenantID: 101, Phone: "13500000001", Status: "active"}
jieyouUser := model.User{TenantID: 202, Phone: "13500000001", Status: "active"}
if err := db.Create(&dachuiUser).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyouUser).Error; err != nil {
t.Fatal(err)
}
dachuiAccount := model.UserPaymentAccount{
TenantID: 101, UserID: dachuiUser.ID, AccountType: "bank",
AccountName: "张三", AccountNo: "encrypted-dachui", Status: "active",
}
jieyouAccount := model.UserPaymentAccount{
TenantID: 202, UserID: jieyouUser.ID, AccountType: "bank",
AccountName: "张三", AccountNo: "encrypted-jieyou", Status: "active",
}
if err := db.Create(&dachuiAccount).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyouAccount).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db, nil)
page, err := repo.List(paymentTenantContext(101), dachuiUser.ID, 1, 10)
if err != nil {
t.Fatalf("list dachui accounts: %v", err)
}
if page.Total != 1 || len(page.Items) != 1 || page.Items[0].ID != dachuiAccount.ID {
t.Fatalf("dachui payment accounts = %+v", page)
}
if _, err := repo.FindByID(paymentTenantContext(202), jieyouUser.ID, dachuiAccount.ID); !errors.Is(err, ErrAccountNotFound) {
t.Fatalf("cross-tenant account lookup error = %v, want ErrAccountNotFound", err)
}
}
func TestPaymentAccountCreateWritesTenant(t *testing.T) {
db := database.NewTestDB()
user := model.User{TenantID: 101, Phone: "13500000002", Status: "active"}
if err := db.Create(&user).Error; err != nil {
t.Fatal(err)
}
repo := NewRepository(db, nil)
account, err := repo.Create(paymentTenantContext(101), user.ID, CreatePaymentAccountRequest{
AccountType: "bank",
AccountName: "李四",
AccountNo: "6222020000000000",
})
if err != nil {
t.Fatalf("create payment account: %v", err)
}
var stored model.UserPaymentAccount
if err := db.First(&stored, account.ID).Error; err != nil {
t.Fatal(err)
}
if stored.TenantID != 101 {
t.Fatalf("stored tenant_id = %d, want 101", stored.TenantID)
}
}
+43 -16
View File
@@ -8,6 +8,7 @@ import (
"hfb_sys/backend/internal/logging"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/invitation"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/crypto"
"go.uber.org/zap"
@@ -32,7 +33,11 @@ func NewRepository(db *gorm.DB, encryptor crypto.Encryptor, idHashKey string) *R
func (r *Repository) FindByUserID(ctx context.Context, userID uint64) (*model.UserRealname, error) {
var record model.UserRealname
if err := r.db.WithContext(ctx).Where("user_id = ?", userID).First(&record).Error; err != nil {
query := r.db.WithContext(ctx).Where("user_id = ?", userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&record).Error; err != nil {
return nil, err
}
return &record, nil
@@ -41,8 +46,11 @@ func (r *Repository) FindByUserID(ctx context.Context, userID uint64) (*model.Us
// IsVerifiedUser 判断当前账号是否已经完成实名认证。
func (r *Repository) IsVerifiedUser(ctx context.Context, userID uint64) (bool, error) {
var userStatus string
if err := r.db.WithContext(ctx).Model(&model.User{}).
Where("id = ?", userID).Pluck("realname_status", &userStatus).Error; err != nil {
userQuery := r.db.WithContext(ctx).Model(&model.User{}).Where("id = ?", userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
if err := userQuery.Pluck("realname_status", &userStatus).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil
}
@@ -52,9 +60,12 @@ func (r *Repository) IsVerifiedUser(ctx context.Context, userID uint64) (bool, e
return true, nil
}
var count int64
err := r.db.WithContext(ctx).Model(&model.UserRealname{}).
Where("user_id = ? AND status = ?", userID, StatusVerified).
Count(&count).Error
realnameQuery := r.db.WithContext(ctx).Model(&model.UserRealname{}).
Where("user_id = ? AND status = ?", userID, StatusVerified)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
realnameQuery = realnameQuery.Where("tenant_id = ?", tenantID)
}
err := realnameQuery.Count(&count).Error
return count > 0, err
}
@@ -67,11 +78,15 @@ func (r *Repository) ExistsVerifiedIdentity(ctx context.Context, userID uint64,
return false, nil
}
idNoHash := FingerprintIDNo(r.idHashKey, idNo)
tenantID := tenancy.IDFromContext(ctx)
var count int64
if err := r.db.WithContext(ctx).Model(&model.UserRealname{}).
Where("status = ? AND id_no_hash = ? AND user_id <> ?", StatusVerified, idNoHash, userID).
Count(&count).Error; err != nil {
query := r.db.WithContext(ctx).Model(&model.UserRealname{}).
Where("status = ? AND id_no_hash = ? AND user_id <> ?", StatusVerified, idNoHash, userID)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Count(&count).Error; err != nil {
return false, err
}
if count > 0 {
@@ -80,9 +95,12 @@ func (r *Repository) ExistsVerifiedIdentity(ctx context.Context, userID uint64,
masked := maskIDNo(idNo)
var candidates []model.UserRealname
if err := r.db.WithContext(ctx).
Where("status = ? AND user_id <> ? AND masked_id_no = ?", StatusVerified, userID, masked).
Find(&candidates).Error; err != nil {
query = r.db.WithContext(ctx).
Where("status = ? AND user_id <> ? AND masked_id_no = ?", StatusVerified, userID, masked)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.Find(&candidates).Error; err != nil {
return false, err
}
for _, candidate := range candidates {
@@ -121,7 +139,9 @@ func (r *Repository) backfillIDNoHash(ctx context.Context, recordID uint64, idNo
// SaveResult 保存实名结果并更新用户实名状态。idNoHash 仅认证通过时写入。
func (r *Repository) SaveResult(ctx context.Context, userID uint64, provider string, result ProviderResult, idNoHash string) (*model.UserRealname, error) {
tenantID := tenancy.IDFromContext(ctx)
record := model.UserRealname{
TenantID: tenantID,
UserID: userID,
Provider: provider,
ProviderOrderNo: result.ProviderOrderNo,
@@ -140,8 +160,11 @@ func (r *Repository) SaveResult(ctx context.Context, userID uint64, provider str
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var existing model.UserRealname
findErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("user_id = ?", userID).First(&existing).Error
findQuery := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ?", userID)
if tenantID > 0 {
findQuery = findQuery.Where("tenant_id = ?", tenantID)
}
findErr := findQuery.First(&existing).Error
switch {
case findErr == nil:
existing.Provider = record.Provider
@@ -178,7 +201,11 @@ func (r *Repository) SaveResult(ctx context.Context, userID uint64, provider str
if result.Status == StatusPending {
userStatus = "pending"
}
if err := tx.Model(&model.User{}).Where("id = ?", userID).Update("realname_status", userStatus).Error; err != nil {
userQuery := tx.Model(&model.User{}).Where("id = ?", userID)
if tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
if err := userQuery.Update("realname_status", userStatus).Error; err != nil {
return err
}
if userStatus == "verified" {
@@ -209,7 +236,7 @@ func isDuplicateIDNoError(err error) bool {
return true
}
text := strings.ToLower(err.Error())
return strings.Contains(text, "1062") && strings.Contains(text, "uk_user_realname_id_no_hash")
return strings.Contains(text, "1062") && strings.Contains(text, "uk_user_realname_tenant_id_no")
}
// IsIDNoDuplicateError 供其他模块复用身份证唯一键冲突判断。
@@ -1,18 +1,24 @@
package realname
import (
"context"
"errors"
"testing"
"time"
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/crypto"
"go.uber.org/zap"
"gorm.io/gorm"
)
func realnameTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
func setupRealnameTestDB(t *testing.T) *gorm.DB {
t.Helper()
db := database.NewTestDB()
@@ -66,6 +72,44 @@ func TestRealnameIdentityMustBeUnique(t *testing.T) {
}
}
func TestRealnameIdentityCanBeUsedAcrossTenants(t *testing.T) {
db := setupRealnameTestDB(t)
svc := newRealnameTestService(t, db)
const phone = "13700000041"
const idNo = "110101199001010060"
dachuiUser := model.User{TenantID: 101, Phone: phone, Status: "active"}
jieyouUser := model.User{TenantID: 202, Phone: phone, Status: "active"}
if err := db.Create(&dachuiUser).Error; err != nil {
t.Fatalf("create dachui user: %v", err)
}
if err := db.Create(&jieyouUser).Error; err != nil {
t.Fatalf("create jieyou user: %v", err)
}
if _, err := svc.Start(realnameTenantContext(101), dachuiUser.ID, "张三", idNo); err != nil {
t.Fatalf("dachui realname: %v", err)
}
if _, err := svc.Start(realnameTenantContext(202), jieyouUser.ID, "张三", idNo); err != nil {
t.Fatalf("jieyou realname: %v", err)
}
otherDachuiUser := model.User{TenantID: 101, Phone: "13700000042", Status: "active"}
if err := db.Create(&otherDachuiUser).Error; err != nil {
t.Fatalf("create second dachui user: %v", err)
}
if _, err := svc.Start(realnameTenantContext(101), otherDachuiUser.ID, "张三", idNo); !errors.Is(err, ErrIDNoAlreadyUsed) {
t.Fatalf("same tenant duplicate identity error = %v, want ErrIDNoAlreadyUsed", err)
}
var records []model.UserRealname
if err := db.Where("id_no_hash IS NOT NULL").Find(&records).Error; err != nil {
t.Fatal(err)
}
if len(records) != 2 || records[0].TenantID == records[1].TenantID {
t.Fatalf("tenant realname records = %+v", records)
}
}
func TestRealnameIdentityCheckSupportsLegacyEncryptedRecord(t *testing.T) {
db := setupRealnameTestDB(t)
svc := newRealnameTestService(t, db)
+70 -13
View File
@@ -9,6 +9,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/internal/timeutil"
"hfb_sys/backend/pkg/money"
@@ -21,6 +22,7 @@ type Repository struct {
}
type Entry struct {
TenantID uint64
UserID uint64
DistributionSiteID uint64
OrderID *uint64
@@ -66,10 +68,15 @@ func (r *Repository) Account(ctx context.Context, userID uint64, siteCode ...str
var account model.WalletAccount
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := ensureAccount(tx, userID, siteID); err != nil {
tenantID := resolveTenantID(tx, tenancy.IDFromContext(ctx), userID)
if err := ensureAccount(tx, userID, tenantID, siteID); err != nil {
return err
}
return tx.Where("user_id = ? AND distribution_site_id = ?", userID, siteID).First(&account).Error
query := tx.Where("user_id = ? AND distribution_site_id = ?", userID, siteID)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
return query.First(&account).Error
})
if err != nil {
return nil, err
@@ -87,7 +94,11 @@ func (r *Repository) Ledger(ctx context.Context, userID uint64, page, pageSize i
return nil, err
}
tenantID := tenancy.IDFromContext(ctx)
query := r.db.WithContext(ctx).Model(&model.WalletLedger{}).Where("user_id = ?", userID)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if siteID > 0 {
query = query.Where("distribution_site_id = ?", siteID)
} else {
@@ -101,6 +112,9 @@ func (r *Repository) Ledger(ctx context.Context, userID uint64, page, pageSize i
offset := (page - 1) * pageSize
var rows []model.WalletLedger
dataQuery := r.db.WithContext(ctx).Where("user_id = ?", userID)
if tenantID > 0 {
dataQuery = dataQuery.Where("tenant_id = ?", tenantID)
}
if siteID > 0 {
dataQuery = dataQuery.Where("distribution_site_id = ?", siteID)
} else {
@@ -122,7 +136,9 @@ func (r *Repository) Withdraw(ctx context.Context, userID uint64, amountCent int
return nil, ErrInvalidAmount
}
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
tenantID := resolveTenantID(tx, tenancy.IDFromContext(ctx), userID)
return AppendEntries(tx, Entry{
TenantID: tenantID,
UserID: userID,
Direction: "out",
AmountCent: amountCent,
@@ -139,6 +155,7 @@ func (r *Repository) Withdraw(ctx context.Context, userID uint64, amountCent int
}
func (r *Repository) AdminLedger(ctx context.Context, query AdminLedgerQuery) (*PaginatedResult, error) {
tenantID := tenancy.IDFromContext(ctx)
db := r.db.WithContext(ctx).Table("wallet_ledger AS wl").
Select(`wl.id, wl.ledger_no, wl.user_id, COALESCE(u.phone, '') AS user_phone,
COALESCE(u.nickname, '') AS user_nickname, wl.order_id, COALESCE(ro.order_no, '') AS order_no,
@@ -148,6 +165,10 @@ func (r *Repository) AdminLedger(ctx context.Context, query AdminLedgerQuery) (*
Joins("LEFT JOIN rental_orders AS ro ON ro.id = wl.order_id")
countDB := r.db.WithContext(ctx).Model(&model.WalletLedger{})
if tenantID > 0 {
db = db.Where("wl.tenant_id = ?", tenantID)
countDB = countDB.Where("tenant_id = ?", tenantID)
}
if query.UserID > 0 {
db = db.Where("wl.user_id = ?", query.UserID)
countDB = countDB.Where("user_id = ?", query.UserID)
@@ -179,11 +200,17 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
if entry.AmountCent <= 0 {
continue
}
if err := ensureAccount(tx, entry.UserID, entry.DistributionSiteID); err != nil {
tenantID := resolveTenantID(tx, entry.TenantID, entry.UserID)
if err := ensureAccount(tx, entry.UserID, tenantID, entry.DistributionSiteID); err != nil {
return err
}
var account model.WalletAccount
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ? AND distribution_site_id = ?", entry.UserID, entry.DistributionSiteID).First(&account).Error; err != nil {
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("user_id = ? AND distribution_site_id = ?", entry.UserID, entry.DistributionSiteID)
if tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&account).Error; err != nil {
return err
}
balanceAfterCent, err := applyEntry(&account, entry)
@@ -199,6 +226,7 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
}
ledger := model.WalletLedger{
LedgerNo: ledgerNo,
TenantID: tenantID,
UserID: entry.UserID,
DistributionSiteID: entry.DistributionSiteID,
OrderID: entry.OrderID,
@@ -217,8 +245,20 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
return nil
}
func ensureAccount(tx *gorm.DB, userID uint64, siteID ...uint64) error {
return EnsureAccountTx(tx, userID, siteID...)
func ensureAccount(tx *gorm.DB, userID uint64, tenantID uint64, siteID ...uint64) error {
var sID uint64
if len(siteID) > 0 {
sID = siteID[0]
}
account := model.WalletAccount{
TenantID: resolveTenantID(tx, tenantID, userID),
UserID: userID,
DistributionSiteID: sID,
AvailableBalanceCent: 0,
FrozenBalanceCent: 0,
Status: "active",
}
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error
}
// EnsureAccountTx 在事务内确保用户钱包账户存在(幂等)。
@@ -227,14 +267,31 @@ func EnsureAccountTx(tx *gorm.DB, userID uint64, siteID ...uint64) error {
if len(siteID) > 0 {
sID = siteID[0]
}
account := model.WalletAccount{
UserID: userID,
DistributionSiteID: sID,
AvailableBalanceCent: 0,
FrozenBalanceCent: 0,
Status: "active",
return ensureAccount(tx, userID, tenantIDFromDB(tx), sID)
}
func resolveTenantID(db *gorm.DB, explicitTenantID uint64, userID uint64) uint64 {
if explicitTenantID > 0 {
return explicitTenantID
}
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error
if tenantID := tenantIDFromDB(db); tenantID > 0 {
return tenantID
}
if userID == 0 {
return 0
}
var tenantID uint64
if err := db.Model(&model.User{}).Select("tenant_id").Where("id = ?", userID).Scan(&tenantID).Error; err != nil {
return 0
}
return tenantID
}
func tenantIDFromDB(db *gorm.DB) uint64 {
if db == nil || db.Statement == nil || db.Statement.Context == nil {
return 0
}
return tenancy.IDFromContext(db.Statement.Context)
}
func applyEntry(account *model.WalletAccount, entry Entry) (int64, error) {
@@ -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)
}
}
+22 -3
View File
@@ -8,6 +8,7 @@ import (
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/wallet"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -16,6 +17,9 @@ import (
// 管理员查询提现列表
func (r *Repository) AdminList(ctx context.Context, query AdminListQuery) (*AdminPaginatedResult, error) {
db := r.db.WithContext(ctx).Model(&model.WithdrawalRequest{})
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
db = db.Where("tenant_id = ?", tenantID)
}
if query.Status != "" {
db = db.Where("status = ?", query.Status)
@@ -55,7 +59,11 @@ func (r *Repository) AdminList(ctx context.Context, query AdminListQuery) (*Admi
// 管理员查询提现详情
func (r *Repository) AdminFindByID(ctx context.Context, id uint64) (*WithdrawalDetailDTO, error) {
var withdrawal model.WithdrawalRequest
if err := r.db.WithContext(ctx).First(&withdrawal, id).Error; err != nil {
query := r.db.WithContext(ctx).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&withdrawal).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWithdrawalNotFound
}
@@ -70,7 +78,11 @@ func (r *Repository) AdminFindByID(ctx context.Context, id uint64) (*WithdrawalD
func (r *Repository) Review(ctx context.Context, adminID, id uint64, req ReviewWithdrawalRequest) (*WithdrawalDetailDTO, error) {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var withdrawal model.WithdrawalRequest
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&withdrawal, id).Error; err != nil {
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&withdrawal).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrWithdrawalNotFound
}
@@ -102,6 +114,7 @@ func (r *Repository) Review(ctx context.Context, adminID, id uint64, req ReviewW
// 如果拒绝,解冻余额
if !approved {
if err := wallet.AppendEntries(tx, wallet.Entry{
TenantID: withdrawal.TenantID,
UserID: withdrawal.UserID,
DistributionSiteID: withdrawal.DistributionSiteID,
Direction: "out",
@@ -111,6 +124,7 @@ func (r *Repository) Review(ctx context.Context, adminID, id uint64, req ReviewW
BizNo: withdrawal.WithdrawNo,
Remark: fmt.Sprintf("提现被拒绝: %s", req.Remark),
}, wallet.Entry{
TenantID: withdrawal.TenantID,
UserID: withdrawal.UserID,
DistributionSiteID: withdrawal.DistributionSiteID,
Direction: "in",
@@ -139,7 +153,11 @@ func (r *Repository) Review(ctx context.Context, adminID, id uint64, req ReviewW
func (r *Repository) ConfirmPayment(ctx context.Context, adminID, id uint64, req ConfirmPaymentRequest) (*WithdrawalDetailDTO, error) {
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var withdrawal model.WithdrawalRequest
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&withdrawal, id).Error; err != nil {
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.First(&withdrawal).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrWithdrawalNotFound
}
@@ -164,6 +182,7 @@ func (r *Repository) ConfirmPayment(ctx context.Context, adminID, id uint64, req
// 扣除冻结余额
if err := wallet.AppendEntries(tx, wallet.Entry{
TenantID: withdrawal.TenantID,
UserID: withdrawal.UserID,
DistributionSiteID: withdrawal.DistributionSiteID,
Direction: "out",
@@ -7,6 +7,7 @@ import (
"strings"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
)
// 转换为用户DTO
@@ -58,7 +59,11 @@ func (r *Repository) toAdminListItems(ctx context.Context, withdrawals []model.W
usersByID := make(map[uint64]model.User, len(userIDs))
var users []model.User
if err := r.db.WithContext(ctx).Select("id, nickname, phone").Where("id IN ?", userIDs).Find(&users).Error; err != nil {
userQuery := r.db.WithContext(ctx).Select("id, nickname, phone").Where("id IN ?", userIDs)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
if err := userQuery.Find(&users).Error; err != nil {
return nil, err
}
for _, user := range users {
@@ -106,9 +111,14 @@ func (r *Repository) toAdminListItems(ctx context.Context, withdrawals []model.W
// 转换为管理员详细DTO
func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest) (*WithdrawalDetailDTO, error) {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
// 查询用户信息
var user model.User
db.Select("nickname, phone").First(&user, w.UserID)
userQuery := db.Select("nickname, phone").Where("id = ?", w.UserID)
if tenantID > 0 {
userQuery = userQuery.Where("tenant_id = ?", tenantID)
}
userQuery.First(&user)
// 查询审核人信息
var reviewedByName string
@@ -133,7 +143,11 @@ func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest)
var certificateURLs []string
if w.PaymentAccountID != nil {
var paymentAccount model.UserPaymentAccount
if err := db.First(&paymentAccount, *w.PaymentAccountID).Error; err == nil {
accountQuery := db.Where("id = ?", *w.PaymentAccountID)
if tenantID > 0 {
accountQuery = accountQuery.Where("tenant_id = ?", tenantID)
}
if err := accountQuery.First(&paymentAccount).Error; err == nil {
// 解密账号
decrypted, err := r.encryptor.Decrypt(paymentAccount.AccountNo)
if err == nil {
@@ -9,12 +9,17 @@ import (
"hfb_sys/backend/internal/database"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/wallet"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/crypto"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func withdrawalTenantContext(tenantID uint64) context.Context {
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
}
type withdrawalFixture struct {
db *gorm.DB
repo *Repository
@@ -405,3 +410,72 @@ func TestWithdrawalDetailIncludesDistributionSiteInfo(t *testing.T) {
t.Fatalf("unexpected detail site info: %+v", detail)
}
}
func TestWithdrawalRequestsAreScopedByTenant(t *testing.T) {
db := database.NewTestDB()
dachuiUser := model.User{TenantID: 101, Phone: "13300000001", Status: "active"}
jieyouUser := model.User{TenantID: 202, Phone: "13300000001", Status: "active"}
if err := db.Create(&dachuiUser).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyouUser).Error; err != nil {
t.Fatal(err)
}
dachuiAccount := model.UserPaymentAccount{
TenantID: 101, UserID: dachuiUser.ID, AccountType: "bank",
AccountName: "张三", AccountNo: "encrypted", Status: "active",
}
jieyouAccount := model.UserPaymentAccount{
TenantID: 202, UserID: jieyouUser.ID, AccountType: "bank",
AccountName: "张三", AccountNo: "encrypted", Status: "active",
}
if err := db.Create(&dachuiAccount).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&jieyouAccount).Error; err != nil {
t.Fatal(err)
}
for _, account := range []model.WalletAccount{
{TenantID: 101, UserID: dachuiUser.ID, AvailableBalanceCent: 10_000, Status: "active"},
{TenantID: 202, UserID: jieyouUser.ID, AvailableBalanceCent: 10_000, Status: "active"},
} {
if err := db.Create(&account).Error; err != nil {
t.Fatal(err)
}
}
repo := NewRepository(db, wallet.NewRepository(db), &crypto.MockEncryptor{})
dachuiCtx := withdrawalTenantContext(101)
jieyouCtx := withdrawalTenantContext(202)
dachuiWithdrawal, err := repo.Create(dachuiCtx, dachuiUser.ID, CreateWithdrawalRequest{
PaymentAccountID: dachuiAccount.ID,
AmountCent: 1000,
})
if err != nil {
t.Fatalf("create dachui withdrawal: %v", err)
}
if _, err := repo.Create(jieyouCtx, jieyouUser.ID, CreateWithdrawalRequest{
PaymentAccountID: jieyouAccount.ID,
AmountCent: 2000,
}); err != nil {
t.Fatalf("create jieyou withdrawal: %v", err)
}
var stored model.WithdrawalRequest
if err := db.First(&stored, dachuiWithdrawal.ID).Error; err != nil {
t.Fatal(err)
}
if stored.TenantID != 101 {
t.Fatalf("withdrawal tenant_id = %d, want 101", stored.TenantID)
}
if _, err := repo.FindByID(jieyouCtx, dachuiUser.ID, dachuiWithdrawal.ID); !errors.Is(err, ErrWithdrawalNotFound) {
t.Fatalf("cross-tenant withdrawal lookup error = %v", err)
}
list, err := repo.AdminList(jieyouCtx, AdminListQuery{Page: 1, Size: 20})
if err != nil {
t.Fatal(err)
}
if list.Total != 1 || len(list.Items) != 1 || list.Items[0].UserID != jieyouUser.ID {
t.Fatalf("jieyou withdrawal list = %+v", list)
}
}
@@ -6,6 +6,7 @@ import (
"time"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
)
@@ -34,7 +35,11 @@ func (r *Repository) AdminReviewContext(ctx context.Context, id uint64, query Wi
query = normalizeReviewContextQuery(query)
var current model.WithdrawalRequest
if err := r.db.WithContext(ctx).First(&current, id).Error; err != nil {
currentQuery := r.db.WithContext(ctx).Where("id = ?", id)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
currentQuery = currentQuery.Where("tenant_id = ?", tenantID)
}
if err := currentQuery.First(&current).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWithdrawalNotFound
}
@@ -79,6 +84,13 @@ func scopeWithdrawalSite(db *gorm.DB, column string, siteID uint64) *gorm.DB {
return db.Where("(" + column + " IS NULL OR " + column + " = 0)")
}
func scopeWithdrawalTenant(db *gorm.DB, column string, tenantID uint64) *gorm.DB {
if tenantID > 0 {
return db.Where(column+" = ?", tenantID)
}
return db
}
func (r *Repository) withdrawalReviewSummary(ctx context.Context, userID, siteID uint64) (WithdrawalReviewSummaryDTO, error) {
db := r.db.WithContext(ctx)
var result WithdrawalReviewSummaryDTO
@@ -101,6 +113,7 @@ func (r *Repository) withdrawalReviewSummary(ctx context.Context, userID, siteID
var walletIncome int64
walletQuery := scopeWithdrawalSite(db.Table("wallet_ledger AS wl"), "wl.distribution_site_id", siteID)
walletQuery = scopeWithdrawalTenant(walletQuery, "wl.tenant_id", tenancy.IDFromContext(ctx))
if err := walletQuery.
Select("COALESCE(SUM(wl.amount_cent), 0)").
Joins("JOIN rental_orders AS o ON o.id = wl.order_id").
@@ -159,6 +172,7 @@ func (r *Repository) withdrawalReviewSummary(ctx context.Context, userID, siteID
RejectedWithdrawalCount int64
}
withdrawalQuery := scopeWithdrawalSite(db.Table("withdrawal_requests"), "distribution_site_id", siteID)
withdrawalQuery = scopeWithdrawalTenant(withdrawalQuery, "tenant_id", tenancy.IDFromContext(ctx))
if err := withdrawalQuery.
Select(`COUNT(*) AS withdrawal_count,
COALESCE(SUM(CASE WHEN status = 'completed' THEN actual_amount_cent ELSE 0 END), 0) AS withdrawn_amount_cent,
@@ -224,12 +238,12 @@ func (r *Repository) withdrawalReviewOrders(ctx context.Context, userID, siteID
OrderID uint64
AmountCent int64
}
if err := r.db.WithContext(ctx).
walletLedgerQuery := r.db.WithContext(ctx).
Table("wallet_ledger").
Select("order_id, COALESCE(SUM(amount_cent), 0) AS amount_cent").
Where("order_id IN ? AND user_id = ? AND direction = ? AND biz_type IN ?", orderIDs, userID, "in", ownerIncomeBizTypes).
Group("order_id").
Scan(&walletRows).Error; err != nil {
Where("order_id IN ? AND user_id = ? AND direction = ? AND biz_type IN ?", orderIDs, userID, "in", ownerIncomeBizTypes)
walletLedgerQuery = scopeWithdrawalTenant(walletLedgerQuery, "tenant_id", tenancy.IDFromContext(ctx))
if err := walletLedgerQuery.Group("order_id").Scan(&walletRows).Error; err != nil {
return nil, err
}
walletIncome := make(map[uint64]int64, len(walletRows))
@@ -343,6 +357,7 @@ func (r *Repository) withdrawalReviewHistory(ctx context.Context, userID, siteID
var rows []model.WithdrawalRequest
offset := (query.WithdrawalPage - 1) * query.PageSize
historyQuery := scopeWithdrawalSite(r.db.WithContext(ctx), "distribution_site_id", siteID)
historyQuery = scopeWithdrawalTenant(historyQuery, "tenant_id", tenancy.IDFromContext(ctx))
if err := historyQuery.
Where("user_id = ?", userID).
Order("created_at DESC, id DESC").
+28 -4
View File
@@ -7,6 +7,7 @@ import (
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/wallet"
"hfb_sys/backend/internal/tenancy"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -30,9 +31,14 @@ func (r *Repository) resolveSiteID(ctx context.Context, siteCode string) (uint64
// 用户创建提现申请
func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdrawalRequest, siteCode ...string) (*WithdrawalDTO, error) {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
// 验证收款账号
var paymentAccount model.UserPaymentAccount
if err := db.Where("id = ? AND user_id = ? AND status = ?", req.PaymentAccountID, userID, "active").
accountQuery := db.Where("id = ? AND user_id = ? AND status = ?", req.PaymentAccountID, userID, "active")
if tenantID > 0 {
accountQuery = accountQuery.Where("tenant_id = ?", tenantID)
}
if err := accountQuery.
First(&paymentAccount).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, errors.New("payment account not found")
@@ -67,6 +73,7 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
withdrawal := model.WithdrawalRequest{
WithdrawNo: withdrawNo,
TenantID: tenantID,
UserID: userID,
DistributionSiteID: siteID,
AmountCent: req.AmountCent,
@@ -90,6 +97,7 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
// 冻结用户余额
if err := wallet.AppendEntries(tx, wallet.Entry{
TenantID: tenantID,
UserID: userID,
DistributionSiteID: siteID,
Direction: "out",
@@ -99,6 +107,7 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
BizNo: withdrawNo,
Remark: "提现冻结",
}, wallet.Entry{
TenantID: tenantID,
UserID: userID,
DistributionSiteID: siteID,
Direction: "in",
@@ -124,6 +133,7 @@ func (r *Repository) Create(ctx context.Context, userID uint64, req CreateWithdr
// 用户查询提现列表
func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int, siteCode ...string) (*PaginatedResult, error) {
db := r.db.WithContext(ctx)
tenantID := tenancy.IDFromContext(ctx)
var code string
if len(siteCode) > 0 {
code = siteCode[0]
@@ -135,6 +145,10 @@ func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int
countDB := db.Model(&model.WithdrawalRequest{}).Where("user_id = ?", userID)
dataDB := db.Where("user_id = ?", userID)
if tenantID > 0 {
countDB = countDB.Where("tenant_id = ?", tenantID)
dataDB = dataDB.Where("tenant_id = ?", tenantID)
}
if siteID > 0 {
countDB = countDB.Where("distribution_site_id = ?", siteID)
dataDB = dataDB.Where("distribution_site_id = ?", siteID)
@@ -174,7 +188,11 @@ func (r *Repository) List(ctx context.Context, userID uint64, page, pageSize int
// 用户查询提现详情
func (r *Repository) FindByID(ctx context.Context, userID, id uint64) (*WithdrawalDTO, error) {
var withdrawal model.WithdrawalRequest
if err := r.db.WithContext(ctx).Where("id = ? AND user_id = ?", id, userID).
query := r.db.WithContext(ctx).Where("id = ? AND user_id = ?", id, userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.
First(&withdrawal).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWithdrawalNotFound
@@ -191,8 +209,12 @@ func (r *Repository) FindByID(ctx context.Context, userID, id uint64) (*Withdraw
func (r *Repository) Cancel(ctx context.Context, userID, id uint64) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var withdrawal model.WithdrawalRequest
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ? AND user_id = ?", id, userID).
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("id = ? AND user_id = ?", id, userID)
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
query = query.Where("tenant_id = ?", tenantID)
}
if err := query.
First(&withdrawal).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrWithdrawalNotFound
@@ -212,6 +234,7 @@ func (r *Repository) Cancel(ctx context.Context, userID, id uint64) error {
// 解冻余额
if err := wallet.AppendEntries(tx, wallet.Entry{
TenantID: withdrawal.TenantID,
UserID: userID,
DistributionSiteID: withdrawal.DistributionSiteID,
Direction: "out",
@@ -221,6 +244,7 @@ func (r *Repository) Cancel(ctx context.Context, userID, id uint64) error {
BizNo: withdrawal.WithdrawNo,
Remark: "用户取消提现",
}, wallet.Entry{
TenantID: withdrawal.TenantID,
UserID: userID,
DistributionSiteID: withdrawal.DistributionSiteID,
Direction: "in",
+3 -1
View File
@@ -69,7 +69,6 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
var tenantRepo *tenancy.Repository
if deps.DB != nil {
tenantRepo = tenancy.NewRepository(deps.DB)
engine.Use(middleware.TenantContext(tenantRepo, cfg.AppEnv, logger))
}
tenantHandler := tenancy.NewHandler()
jwtManager := auth.NewJWTManager(cfg.JWTSecret)
@@ -356,6 +355,9 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
if distributionRepo != nil {
engine.Use(middleware.SiteDomainFallback(distributionRepo, logger))
}
if tenantRepo != nil {
engine.Use(middleware.TenantContext(tenantRepo, cfg.AppEnv, logger, "dachui"))
}
distributionHandler := distribution.NewHandler(distributionService)
if invitationHandler != nil && distributionService != nil {
invitationHandler.SetSiteScoper(distributionService)
+18
View File
@@ -3,6 +3,7 @@ package tenancy
import (
"context"
"encoding/json"
"fmt"
"gorm.io/datatypes"
)
@@ -37,6 +38,23 @@ func MustFromContext(ctx context.Context) Scope {
return scope
}
func IDFromContext(ctx context.Context) uint64 {
scope, ok := FromContext(ctx)
if !ok {
return 0
}
return scope.TenantID
}
// ScopeKey returns a stable cache scope suffix. An empty string keeps legacy
// callers and tests on their existing unqualified keys.
func ScopeKey(ctx context.Context) string {
if tenantID := IDFromContext(ctx); tenantID > 0 {
return fmt.Sprintf("tenant:%d", tenantID)
}
return ""
}
func (s Scope) Profile() map[string]any {
return decodeJSONMap(s.ProfileJSON)
}