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
+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)
}
}