fix(auth): 修复历史分销用户登录后立即退出
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
|||||||
|
|
||||||
"hfb_sys/backend/internal/logging"
|
"hfb_sys/backend/internal/logging"
|
||||||
"hfb_sys/backend/internal/modules/auth"
|
"hfb_sys/backend/internal/modules/auth"
|
||||||
|
"hfb_sys/backend/internal/sitecode"
|
||||||
"hfb_sys/backend/internal/tenancy"
|
"hfb_sys/backend/internal/tenancy"
|
||||||
"hfb_sys/backend/pkg/response"
|
"hfb_sys/backend/pkg/response"
|
||||||
|
|
||||||
@@ -217,7 +218,11 @@ func userTokenTenantMatches(c *gin.Context, tokenTenantID uint64) bool {
|
|||||||
if tokenTenantID == 0 {
|
if tokenTenantID == 0 {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return requestTenantID > 0 && requestTenantID == tokenTenantID
|
if requestTenantID > 0 {
|
||||||
|
return requestTenantID == tokenTenantID
|
||||||
|
}
|
||||||
|
// 历史分销用户的 tenant_id 可能仍指向大锤,具体归属由令牌校验时的站点过滤确认。
|
||||||
|
return sitecode.BoundSiteCodeFromContext(c.Request.Context()) != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gin.HandlerFunc {
|
func AdminAuth(jwtManager *auth.JWTManager, validate AdminTokenValidatorFunc) gin.HandlerFunc {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/modules/auth"
|
"hfb_sys/backend/internal/modules/auth"
|
||||||
|
"hfb_sys/backend/internal/sitecode"
|
||||||
"hfb_sys/backend/internal/tenancy"
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -20,6 +21,14 @@ func useRequestTenant(tenantID uint64) gin.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func useBoundSiteCode(code string) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
ctx := sitecode.WithBoundSiteCode(c.Request.Context(), code)
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestUserAuthRejectsQueryToken(t *testing.T) {
|
func TestUserAuthRejectsQueryToken(t *testing.T) {
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
manager := auth.NewJWTManager("test-jwt-secret-for-query-token-rejection")
|
manager := auth.NewJWTManager("test-jwt-secret-for-query-token-rejection")
|
||||||
@@ -111,3 +120,39 @@ func TestUserAndAdminTokensRejectCrossTenantRequests(t *testing.T) {
|
|||||||
t.Fatalf("cross-tenant admin token status = %d, want 401", adminResponse.Code)
|
t.Fatalf("cross-tenant admin token status = %d, want 401", adminResponse.Code)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestUserAuthAllowsLegacyTenantTokenOnBoundDistributionSite(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
manager := auth.NewJWTManager("legacy-distribution-auth-test-secret")
|
||||||
|
pair, err := manager.GenerateTenantPairWithVersion(1, "13800000000", "user", 1, 101)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
newEngine := func(boundSiteCode string) *gin.Engine {
|
||||||
|
engine := gin.New()
|
||||||
|
if boundSiteCode != "" {
|
||||||
|
engine.Use(useBoundSiteCode(boundSiteCode))
|
||||||
|
}
|
||||||
|
engine.GET("/protected", Auth(manager, nil), func(c *gin.Context) {
|
||||||
|
c.Status(http.StatusNoContent)
|
||||||
|
})
|
||||||
|
return engine
|
||||||
|
}
|
||||||
|
|
||||||
|
request := httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||||
|
request.Header.Set("Authorization", "Bearer "+pair.AccessToken)
|
||||||
|
boundResponse := httptest.NewRecorder()
|
||||||
|
newEngine("legacy_site_a").ServeHTTP(boundResponse, request)
|
||||||
|
if boundResponse.Code != http.StatusNoContent {
|
||||||
|
t.Fatalf("bound distribution token status = %d, want 204", boundResponse.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
request = httptest.NewRequest(http.MethodGet, "/protected", nil)
|
||||||
|
request.Header.Set("Authorization", "Bearer "+pair.AccessToken)
|
||||||
|
unboundResponse := httptest.NewRecorder()
|
||||||
|
newEngine("").ServeHTTP(unboundResponse, request)
|
||||||
|
if unboundResponse.Code != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("unbound distribution token status = %d, want 401", unboundResponse.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -77,10 +77,22 @@ func SiteDomainFallback(resolver SiteDomainResolver, logger *zap.Logger) gin.Han
|
|||||||
}
|
}
|
||||||
// 已登记的站点域名是权威来源。即使前端带着旧站点头或 query,
|
// 已登记的站点域名是权威来源。即使前端带着旧站点头或 query,
|
||||||
// 也必须先确认当前 Host 属于哪个分销站点,否则后续 known-host 校验会误拒绝请求。
|
// 也必须先确认当前 Host 属于哪个分销站点,否则后续 known-host 校验会误拒绝请求。
|
||||||
if code := resolveSiteCodeByHost(c, resolver, cache, logger); code != "" {
|
hostCode := resolveSiteCodeByHost(c, resolver, cache, logger)
|
||||||
|
code := hostCode
|
||||||
|
if code != "" {
|
||||||
c.Request.Header.Del(sitecode.LegacyHeaderName)
|
c.Request.Header.Del(sitecode.LegacyHeaderName)
|
||||||
c.Request.Header.Set(sitecode.HeaderName, code)
|
c.Request.Header.Set(sitecode.HeaderName, code)
|
||||||
c.Request = c.Request.WithContext(sitecode.WithDomainScope(c.Request.Context()))
|
} else {
|
||||||
|
// 未登记域名仍允许通过显式站点参数访问预览或开发环境,
|
||||||
|
// 但后续鉴权会继续校验令牌用户是否确实属于该站点。
|
||||||
|
code = sitecode.FromRequest(c)
|
||||||
|
}
|
||||||
|
if code != "" {
|
||||||
|
ctx := sitecode.WithBoundSiteCode(c.Request.Context(), code)
|
||||||
|
if hostCode != "" {
|
||||||
|
ctx = sitecode.WithDomainScope(ctx)
|
||||||
|
}
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
}
|
}
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,6 +71,24 @@ func TestSiteDomainFallbackResolvesByHost(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSiteDomainFallbackBindsResolvedSiteCodeToContext(t *testing.T) {
|
||||||
|
resolver := &fakeSiteDomainResolver{byDomain: map[string]string{"tysh.hao858.com": "gz_dist"}}
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
engine := gin.New()
|
||||||
|
engine.Use(SiteDomainFallback(resolver, nil))
|
||||||
|
engine.GET("/probe", func(c *gin.Context) {
|
||||||
|
c.String(http.StatusOK, sitecode.BoundSiteCodeFromContext(c.Request.Context()))
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||||
|
req.Host = "tysh.hao858.com"
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
engine.ServeHTTP(recorder, req)
|
||||||
|
if got := recorder.Body.String(); got != "gz_dist" {
|
||||||
|
t.Fatalf("bound site code = %q, want gz_dist", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestSiteDomainFallbackKnownHostOverridesExplicitSiteCode(t *testing.T) {
|
func TestSiteDomainFallbackKnownHostOverridesExplicitSiteCode(t *testing.T) {
|
||||||
resolver := &fakeSiteDomainResolver{byDomain: map[string]string{"tysh.hao858.com": "gz_dist"}}
|
resolver := &fakeSiteDomainResolver{byDomain: map[string]string{"tysh.hao858.com": "gz_dist"}}
|
||||||
engine := newSiteFallbackRouter(resolver)
|
engine := newSiteFallbackRouter(resolver)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/sitecode"
|
||||||
"hfb_sys/backend/internal/tenancy"
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -32,12 +33,23 @@ func NewUserRepository(db *gorm.DB) *UserRepository {
|
|||||||
return &UserRepository{db: db}
|
return &UserRepository{db: db}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func scopeUserQueryToBoundSite(ctx context.Context, query *gorm.DB) *gorm.DB {
|
||||||
|
code := sitecode.BoundSiteCodeFromContext(ctx)
|
||||||
|
if code == "" {
|
||||||
|
return query
|
||||||
|
}
|
||||||
|
return query.
|
||||||
|
Joins("JOIN distribution_sites AS auth_site ON auth_site.id = users.distribution_site_id").
|
||||||
|
Where("auth_site.site_code = ? AND auth_site.status = ?", code, "active")
|
||||||
|
}
|
||||||
|
|
||||||
func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User, error) {
|
func (r *UserRepository) FindByID(ctx context.Context, id uint64) (*model.User, error) {
|
||||||
var user model.User
|
var user model.User
|
||||||
query := r.db.WithContext(ctx)
|
query := r.db.WithContext(ctx)
|
||||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||||
}
|
}
|
||||||
|
query = scopeUserQueryToBoundSite(ctx, query)
|
||||||
if err := query.First(&user, id).Error; err != nil {
|
if err := query.First(&user, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -54,8 +66,9 @@ func (r *UserRepository) FindActiveForToken(ctx context.Context, id uint64, toke
|
|||||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||||
}
|
}
|
||||||
|
query = scopeUserQueryToBoundSite(ctx, query)
|
||||||
if err := query.
|
if err := query.
|
||||||
Select("id, phone, status, token_version").
|
Select("users.id, users.phone, users.status, users.token_version").
|
||||||
First(&user, id).Error; err != nil {
|
First(&user, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -73,6 +86,7 @@ func (r *UserRepository) UpdateProfile(ctx context.Context, id uint64, nickname
|
|||||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||||
}
|
}
|
||||||
|
query = scopeUserQueryToBoundSite(ctx, query)
|
||||||
if err := query.Updates(map[string]any{
|
if err := query.Updates(map[string]any{
|
||||||
"nickname": nickname,
|
"nickname": nickname,
|
||||||
"avatar_url": avatarURL,
|
"avatar_url": avatarURL,
|
||||||
@@ -187,6 +201,7 @@ func (r *UserRepository) SetPassword(ctx context.Context, userID uint64, hash st
|
|||||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||||
}
|
}
|
||||||
|
query = scopeUserQueryToBoundSite(ctx, query)
|
||||||
return query.Updates(map[string]any{
|
return query.Updates(map[string]any{
|
||||||
"password_hash": hash,
|
"password_hash": hash,
|
||||||
"token_version": gorm.Expr("token_version + 1"),
|
"token_version": gorm.Expr("token_version + 1"),
|
||||||
@@ -199,6 +214,7 @@ func (r *UserRepository) RevokeTokens(ctx context.Context, userID uint64) error
|
|||||||
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 {
|
||||||
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
query = query.Where("tenant_id = ? AND distribution_site_id = 0", tenantID)
|
||||||
}
|
}
|
||||||
|
query = scopeUserQueryToBoundSite(ctx, query)
|
||||||
return query.UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error
|
return query.UpdateColumn("token_version", gorm.Expr("token_version + 1")).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import (
|
|||||||
smsprovider "hfb_sys/backend/internal/integrations/sms"
|
smsprovider "hfb_sys/backend/internal/integrations/sms"
|
||||||
"hfb_sys/backend/internal/logging"
|
"hfb_sys/backend/internal/logging"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/sitecode"
|
||||||
"hfb_sys/backend/internal/tenancy"
|
"hfb_sys/backend/internal/tenancy"
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
@@ -260,7 +261,9 @@ func (s *Service) RefreshToken(ctx context.Context, refreshToken string) (TokenP
|
|||||||
}
|
}
|
||||||
tenantID := tenancy.IDFromContext(ctx)
|
tenantID := tenancy.IDFromContext(ctx)
|
||||||
if claims.TenantID > 0 && claims.TenantID != tenantID {
|
if claims.TenantID > 0 && claims.TenantID != tenantID {
|
||||||
return TokenPair{}, ErrTokenVersionMismatch
|
if tenantID != 0 || sitecode.BoundSiteCodeFromContext(ctx) == "" {
|
||||||
|
return TokenPair{}, ErrTokenVersionMismatch
|
||||||
|
}
|
||||||
}
|
}
|
||||||
user, err := s.users.FindActiveForToken(ctx, claims.UserID, claims.TokenVersion)
|
user, err := s.users.FindActiveForToken(ctx, claims.UserID, claims.TokenVersion)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
"hfb_sys/backend/internal/database"
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
"hfb_sys/backend/internal/sitecode"
|
||||||
"hfb_sys/backend/internal/tenancy"
|
"hfb_sys/backend/internal/tenancy"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -122,3 +123,47 @@ func TestLegacyDistributionUserCannotEnterTenantSite(t *testing.T) {
|
|||||||
t.Fatalf("legacy distribution domain login failed: %v", err)
|
t.Fatalf("legacy distribution domain login failed: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLegacyDistributionUserSessionIsScopedToBoundSite(t *testing.T) {
|
||||||
|
db := database.NewTestDB()
|
||||||
|
sites := []model.DistributionSite{
|
||||||
|
{SiteCode: "legacy_session_a", SiteName: "历史分销 A", Domain: "legacy-session-a.example.com", Status: "active"},
|
||||||
|
{SiteCode: "legacy_session_b", SiteName: "历史分销 B", Domain: "legacy-session-b.example.com", Status: "active"},
|
||||||
|
}
|
||||||
|
if err := db.Create(&sites).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
legacy := model.User{
|
||||||
|
TenantID: 101, Phone: "13600000019", Status: "active",
|
||||||
|
DistributionSiteID: sites[0].ID, TokenVersion: 1,
|
||||||
|
}
|
||||||
|
if err := db.Create(&legacy).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
repo := NewUserRepository(db)
|
||||||
|
ctxA := sitecode.WithBoundSiteCode(context.Background(), sites[0].SiteCode)
|
||||||
|
ctxB := sitecode.WithBoundSiteCode(context.Background(), sites[1].SiteCode)
|
||||||
|
if _, err := repo.FindActiveForToken(ctxA, legacy.ID, legacy.TokenVersion); err != nil {
|
||||||
|
t.Fatalf("bound own site token validation failed: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.FindActiveForToken(ctxB, legacy.ID, legacy.TokenVersion); !IsNotFound(err) {
|
||||||
|
t.Fatalf("cross-site token validation error = %v, want not found", err)
|
||||||
|
}
|
||||||
|
if _, err := repo.FindActiveForToken(authTenantContext(legacy.TenantID), legacy.ID, legacy.TokenVersion); !IsNotFound(err) {
|
||||||
|
t.Fatalf("tenant-site token validation error = %v, want not found", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
manager := NewJWTManager("legacy-distribution-session-test-secret")
|
||||||
|
pair, err := manager.GenerateTenantPairWithVersion(legacy.ID, legacy.Phone, "user", legacy.TokenVersion, legacy.TenantID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
service := NewService(repo, nil, manager, nil, nil)
|
||||||
|
if _, err := service.RefreshToken(ctxA, pair.RefreshToken); err != nil {
|
||||||
|
t.Fatalf("bound own site refresh failed: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := service.RefreshToken(ctxB, pair.RefreshToken); err == nil {
|
||||||
|
t.Fatal("cross-site refresh must fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ const LegacyHeaderName = "X-Site-Code"
|
|||||||
|
|
||||||
type tenantScopeContextKey struct{}
|
type tenantScopeContextKey struct{}
|
||||||
type domainScopeContextKey struct{}
|
type domainScopeContextKey struct{}
|
||||||
|
type boundSiteCodeContextKey struct{}
|
||||||
|
|
||||||
// WithTenantScope 标记当前请求已识别为经营租户。
|
// WithTenantScope 标记当前请求已识别为经营租户。
|
||||||
// 经营租户与历史分销站点使用不同归属模型,识别成功后必须忽略旧分销站点编码。
|
// 经营租户与历史分销站点使用不同归属模型,识别成功后必须忽略旧分销站点编码。
|
||||||
@@ -50,6 +51,17 @@ func HasDomainScope(ctx context.Context) bool {
|
|||||||
return enabled
|
return enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WithBoundSiteCode 记录本次请求已绑定的历史分销站点编码。
|
||||||
|
// 与请求头不同,该值位于服务端上下文,可供鉴权校验用户是否属于本站。
|
||||||
|
func WithBoundSiteCode(ctx context.Context, code string) context.Context {
|
||||||
|
return context.WithValue(ctx, boundSiteCodeContextKey{}, strings.TrimSpace(code))
|
||||||
|
}
|
||||||
|
|
||||||
|
func BoundSiteCodeFromContext(ctx context.Context) string {
|
||||||
|
code, _ := ctx.Value(boundSiteCodeContextKey{}).(string)
|
||||||
|
return strings.TrimSpace(code)
|
||||||
|
}
|
||||||
|
|
||||||
// FromRequest 按权威优先级解析站点编码:
|
// FromRequest 按权威优先级解析站点编码:
|
||||||
// X-Distribution-Site-Code 头 → X-Site-Code 旧头 → distribution_site_code / site_code query。
|
// X-Distribution-Site-Code 头 → X-Site-Code 旧头 → distribution_site_code / site_code query。
|
||||||
// 所有来源均做 TrimSpace,返回空串表示主站。经营租户请求始终返回空串,
|
// 所有来源均做 TrimSpace,返回空串表示主站。经营租户请求始终返回空串,
|
||||||
|
|||||||
Reference in New Issue
Block a user