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