feat(sms): 支持双站点独立配置登录短信
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type TenantSMSConfig struct {
|
||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||
TenantID uint64 `gorm:"not null;uniqueIndex:uk_tenant_sms_configs_tenant" json:"tenant_id"`
|
||||
Enabled bool `gorm:"not null;default:false" json:"enabled"`
|
||||
Provider string `gorm:"size:32;not null;default:'aliyun'" json:"provider"`
|
||||
AccessKeyID string `gorm:"size:128;not null;default:''" json:"access_key_id"`
|
||||
AccessKeySecret string `gorm:"size:1024;not null;default:''" json:"-"`
|
||||
Endpoint string `gorm:"size:255;not null;default:'dysmsapi.aliyuncs.com'" json:"endpoint"`
|
||||
SignName string `gorm:"size:64;not null;default:''" json:"sign_name"`
|
||||
LoginTemplateCode string `gorm:"size:64;not null;default:''" json:"login_template_code"`
|
||||
UpdatedBy *uint64 `json:"updated_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (TenantSMSConfig) TableName() string {
|
||||
return "tenant_sms_configs"
|
||||
}
|
||||
@@ -55,13 +55,18 @@ type SiteSMSProviderResolver interface {
|
||||
ResolveSMSProvider(ctx context.Context, siteCode, domain string) (smsprovider.Provider, error)
|
||||
}
|
||||
|
||||
type TenantSMSProviderResolver interface {
|
||||
ResolveSMSProvider(ctx context.Context) (smsprovider.Provider, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users *UserRepository
|
||||
redis *redis.Client
|
||||
jwt *JWTManager
|
||||
sms smsprovider.Provider
|
||||
smsResolver SiteSMSProviderResolver
|
||||
log *zap.Logger
|
||||
users *UserRepository
|
||||
redis *redis.Client
|
||||
jwt *JWTManager
|
||||
sms smsprovider.Provider
|
||||
tenantSMSResolver TenantSMSProviderResolver
|
||||
smsResolver SiteSMSProviderResolver
|
||||
log *zap.Logger
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
@@ -77,6 +82,10 @@ func (s *Service) SetSiteSMSResolver(resolver SiteSMSProviderResolver) {
|
||||
s.smsResolver = resolver
|
||||
}
|
||||
|
||||
func (s *Service) SetTenantSMSResolver(resolver TenantSMSProviderResolver) {
|
||||
s.tenantSMSResolver = resolver
|
||||
}
|
||||
|
||||
func (s *Service) Captcha(ctx context.Context) (*captcha.Item, error) {
|
||||
if s.redis == nil {
|
||||
return nil, ErrDependencyUnavailable
|
||||
@@ -139,7 +148,19 @@ func (s *Service) SendSMSCode(ctx context.Context, phone string, captchaID strin
|
||||
if len(siteContext) > 1 {
|
||||
domain = strings.TrimSpace(siteContext[1])
|
||||
}
|
||||
if s.smsResolver != nil && (siteCode != "" || domain != "") {
|
||||
if tenantID > 0 && s.tenantSMSResolver != nil {
|
||||
customProvider, resolveErr := s.tenantSMSResolver.ResolveSMSProvider(ctx)
|
||||
if resolveErr != nil {
|
||||
if s.log != nil {
|
||||
s.log.Warn("解析本站独立短信服务商失败,将回退至主站默认通道",
|
||||
zap.Uint64("tenant_id", tenantID),
|
||||
zap.Error(resolveErr),
|
||||
)
|
||||
}
|
||||
} else if customProvider != nil {
|
||||
provider = customProvider
|
||||
}
|
||||
} else if s.smsResolver != nil && (siteCode != "" || domain != "") {
|
||||
customProvider, resolveErr := s.smsResolver.ResolveSMSProvider(ctx, siteCode, domain)
|
||||
if resolveErr != nil {
|
||||
if s.log != nil {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
smsprovider "hfb_sys/backend/internal/integrations/sms"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
@@ -30,6 +31,16 @@ type mockResolver struct {
|
||||
calledSites []string
|
||||
}
|
||||
|
||||
type mockTenantResolver struct {
|
||||
customProvider smsprovider.Provider
|
||||
called bool
|
||||
}
|
||||
|
||||
func (m *mockTenantResolver) ResolveSMSProvider(ctx context.Context) (smsprovider.Provider, error) {
|
||||
m.called = true
|
||||
return m.customProvider, nil
|
||||
}
|
||||
|
||||
func (m *mockResolver) ResolveSMSProvider(ctx context.Context, siteCode, domain string) (smsprovider.Provider, error) {
|
||||
m.calledSites = append(m.calledSites, siteCode)
|
||||
if siteCode == "site_custom" {
|
||||
@@ -38,6 +49,45 @@ func (m *mockResolver) ResolveSMSProvider(ctx context.Context, siteCode, domain
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestSendSMSCode_TenantResolutionOverridesDefault(t *testing.T) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: "127.0.0.1:16379",
|
||||
DB: 15,
|
||||
})
|
||||
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: 202})
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
t.Skipf("跳过测试:未检测到测试 Redis: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = rdb.FlushDB(context.Background()).Err()
|
||||
_ = rdb.Close()
|
||||
})
|
||||
_ = rdb.FlushDB(ctx)
|
||||
|
||||
defaultProv := &recordProvider{}
|
||||
customProv := &recordProvider{}
|
||||
tenantResolver := &mockTenantResolver{customProvider: customProv}
|
||||
svc := NewService(nil, rdb, nil, defaultProv, zap.NewNop())
|
||||
svc.SetTenantSMSResolver(tenantResolver)
|
||||
|
||||
if err := rdb.Set(ctx, "captcha:auth:sms:tenant-cap", "ABCD", time.Minute).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
phone := "13800138202"
|
||||
if err := svc.SendSMSCode(ctx, phone, "tenant-cap", "ABCD"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !tenantResolver.called {
|
||||
t.Fatal("tenant resolver was not called")
|
||||
}
|
||||
if len(customProv.sentPhones) != 1 || customProv.sentPhones[0] != phone {
|
||||
t.Fatalf("custom provider sent = %v", customProv.sentPhones)
|
||||
}
|
||||
if len(defaultProv.sentPhones) != 0 {
|
||||
t.Fatalf("default provider sent = %v", defaultProv.sentPhones)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendSMSCode_SiteResolutionAndFallback(t *testing.T) {
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: "127.0.0.1:16379",
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package tenantsms
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrInvalidConfig = errors.New("invalid tenant sms config")
|
||||
|
||||
type Config struct {
|
||||
Enabled bool
|
||||
Provider string
|
||||
AccessKeyID string
|
||||
AccessKeySecret string
|
||||
Endpoint string
|
||||
SignName string
|
||||
LoginTemplateCode string
|
||||
}
|
||||
|
||||
type DTO struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Provider string `json:"provider"`
|
||||
AccessKeyID string `json:"access_key_id"`
|
||||
MaskedSecret string `json:"masked_secret"`
|
||||
HasSecret bool `json:"has_secret"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
SignName string `json:"sign_name"`
|
||||
LoginTemplateCode string `json:"login_template_code"`
|
||||
}
|
||||
|
||||
type UpdateRequest struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Provider *string `json:"provider"`
|
||||
AccessKeyID *string `json:"access_key_id"`
|
||||
AccessKeySecret *string `json:"access_key_secret"`
|
||||
Endpoint *string `json:"endpoint"`
|
||||
SignName *string `json:"sign_name"`
|
||||
LoginTemplateCode *string `json:"login_template_code"`
|
||||
}
|
||||
|
||||
func DefaultConfig() Config {
|
||||
return Config{Provider: "aliyun", Endpoint: "dysmsapi.aliyuncs.com"}
|
||||
}
|
||||
|
||||
func normalizeConfig(cfg Config) (Config, error) {
|
||||
cfg.Provider = strings.ToLower(strings.TrimSpace(cfg.Provider))
|
||||
if cfg.Provider == "" {
|
||||
cfg.Provider = "aliyun"
|
||||
}
|
||||
if cfg.Provider != "aliyun" {
|
||||
return Config{}, ErrInvalidConfig
|
||||
}
|
||||
cfg.AccessKeyID = strings.TrimSpace(cfg.AccessKeyID)
|
||||
cfg.AccessKeySecret = strings.TrimSpace(cfg.AccessKeySecret)
|
||||
cfg.SignName = strings.TrimSpace(cfg.SignName)
|
||||
cfg.LoginTemplateCode = strings.TrimSpace(cfg.LoginTemplateCode)
|
||||
cfg.Endpoint = strings.TrimSpace(cfg.Endpoint)
|
||||
if cfg.Endpoint == "" {
|
||||
cfg.Endpoint = "dysmsapi.aliyuncs.com"
|
||||
}
|
||||
if cfg.Enabled {
|
||||
if cfg.AccessKeyID == "" || cfg.AccessKeySecret == "" || cfg.SignName == "" || cfg.LoginTemplateCode == "" {
|
||||
return Config{}, ErrInvalidConfig
|
||||
}
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (cfg Config) DTO() DTO {
|
||||
return DTO{
|
||||
Enabled: cfg.Enabled,
|
||||
Provider: cfg.Provider,
|
||||
AccessKeyID: cfg.AccessKeyID,
|
||||
MaskedSecret: maskSecret(cfg.AccessKeySecret),
|
||||
HasSecret: cfg.AccessKeySecret != "",
|
||||
Endpoint: cfg.Endpoint,
|
||||
SignName: cfg.SignName,
|
||||
LoginTemplateCode: cfg.LoginTemplateCode,
|
||||
}
|
||||
}
|
||||
|
||||
func maskSecret(secret string) string {
|
||||
if secret == "" {
|
||||
return ""
|
||||
}
|
||||
if len(secret) <= 6 {
|
||||
return "******"
|
||||
}
|
||||
return secret[:3] + "******" + secret[len(secret)-3:]
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package tenantsms
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewHandler(repo *Repository) *Handler {
|
||||
return &Handler{repo: repo}
|
||||
}
|
||||
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
if tenancy.IDFromContext(c.Request.Context()) == 0 {
|
||||
response.BadRequest(c, "当前后台缺少经营站点上下文")
|
||||
return
|
||||
}
|
||||
item, err := h.repo.GetDTO(c.Request.Context())
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, item)
|
||||
}
|
||||
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
adminID, ok := c.Get(middleware.ContextAdminID)
|
||||
actorID, valid := adminID.(uint64)
|
||||
if !ok || !valid || actorID == 0 {
|
||||
response.Unauthorized(c, "缺少管理员上下文")
|
||||
return
|
||||
}
|
||||
var req UpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "短信配置格式无效")
|
||||
return
|
||||
}
|
||||
item, err := h.repo.Update(c.Request.Context(), actorID, req, auditlog.Meta{
|
||||
IP: c.ClientIP(),
|
||||
UserAgent: c.GetHeader("User-Agent"),
|
||||
RequestID: middleware.GetRequestID(c),
|
||||
})
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
return
|
||||
}
|
||||
response.OK(c, item)
|
||||
}
|
||||
|
||||
func writeError(c *gin.Context, err error) {
|
||||
response.RecordError(c, err)
|
||||
if errors.Is(err, ErrInvalidConfig) {
|
||||
response.BadRequest(c, "启用独立短信时,AccessKey、签名和登录模板不能为空")
|
||||
return
|
||||
}
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "登录短信配置服务暂时不可用")
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package tenantsms
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
encryptor crypto.Encryptor
|
||||
}
|
||||
|
||||
func NewRepository(db *gorm.DB, encryptor crypto.Encryptor) *Repository {
|
||||
return &Repository{db: db, encryptor: encryptor}
|
||||
}
|
||||
|
||||
func (r *Repository) Get(ctx context.Context) (Config, error) {
|
||||
if r == nil || r.db == nil || r.encryptor == nil {
|
||||
return Config{}, errors.New("tenant sms database unavailable")
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return Config{}, ErrInvalidConfig
|
||||
}
|
||||
var row model.TenantSMSConfig
|
||||
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&row).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return DefaultConfig(), nil
|
||||
}
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
return r.decryptRow(row)
|
||||
}
|
||||
|
||||
func (r *Repository) GetDTO(ctx context.Context) (DTO, error) {
|
||||
cfg, err := r.Get(ctx)
|
||||
if err != nil {
|
||||
return DTO{}, err
|
||||
}
|
||||
return cfg.DTO(), nil
|
||||
}
|
||||
|
||||
func (r *Repository) Update(ctx context.Context, actorID uint64, req UpdateRequest, meta auditlog.Meta) (DTO, error) {
|
||||
if r == nil || r.db == nil || r.encryptor == nil {
|
||||
return DTO{}, errors.New("tenant sms dependencies unavailable")
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 || actorID == 0 {
|
||||
return DTO{}, ErrInvalidConfig
|
||||
}
|
||||
|
||||
var result Config
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var row model.TenantSMSConfig
|
||||
err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("tenant_id = ?", tenantID).
|
||||
First(&row).Error
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
cfg := DefaultConfig()
|
||||
if err == nil {
|
||||
decrypted, decryptErr := r.decryptRow(row)
|
||||
if decryptErr != nil {
|
||||
return decryptErr
|
||||
}
|
||||
cfg = decrypted
|
||||
}
|
||||
cfg = applyUpdate(cfg, req)
|
||||
normalized, normalizeErr := normalizeConfig(cfg)
|
||||
if normalizeErr != nil {
|
||||
return normalizeErr
|
||||
}
|
||||
encrypted, encryptErr := r.encryptor.Encrypt(normalized.AccessKeySecret)
|
||||
if encryptErr != nil {
|
||||
return fmt.Errorf("encrypt tenant sms secret: %w", encryptErr)
|
||||
}
|
||||
|
||||
row.TenantID = tenantID
|
||||
row.Enabled = normalized.Enabled
|
||||
row.Provider = normalized.Provider
|
||||
row.AccessKeyID = normalized.AccessKeyID
|
||||
row.AccessKeySecret = encrypted
|
||||
row.Endpoint = normalized.Endpoint
|
||||
row.SignName = normalized.SignName
|
||||
row.LoginTemplateCode = normalized.LoginTemplateCode
|
||||
row.UpdatedBy = &actorID
|
||||
if row.ID == 0 {
|
||||
if createErr := tx.Create(&row).Error; createErr != nil {
|
||||
return createErr
|
||||
}
|
||||
} else if saveErr := tx.Save(&row).Error; saveErr != nil {
|
||||
return saveErr
|
||||
}
|
||||
|
||||
result = normalized
|
||||
return auditlog.Append(tx, auditlog.Entry{
|
||||
ActorType: "admin",
|
||||
ActorID: actorID,
|
||||
Action: "tenant_sms_config.update",
|
||||
BizType: "tenant_sms_config",
|
||||
BizID: &row.ID,
|
||||
Meta: meta,
|
||||
Detail: map[string]any{
|
||||
"tenant_id": tenantID,
|
||||
"enabled": normalized.Enabled,
|
||||
"provider": normalized.Provider,
|
||||
"access_key_id": normalized.AccessKeyID,
|
||||
"has_secret": normalized.AccessKeySecret != "",
|
||||
"endpoint": normalized.Endpoint,
|
||||
"sign_name": normalized.SignName,
|
||||
"login_template_code": normalized.LoginTemplateCode,
|
||||
},
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return DTO{}, err
|
||||
}
|
||||
return result.DTO(), nil
|
||||
}
|
||||
|
||||
func (r *Repository) decryptRow(row model.TenantSMSConfig) (Config, error) {
|
||||
secret, err := r.encryptor.Decrypt(row.AccessKeySecret)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("decrypt tenant sms secret: %w", err)
|
||||
}
|
||||
return Config{
|
||||
Enabled: row.Enabled,
|
||||
Provider: row.Provider,
|
||||
AccessKeyID: row.AccessKeyID,
|
||||
AccessKeySecret: secret,
|
||||
Endpoint: row.Endpoint,
|
||||
SignName: row.SignName,
|
||||
LoginTemplateCode: row.LoginTemplateCode,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func applyUpdate(cfg Config, req UpdateRequest) Config {
|
||||
if req.Enabled != nil {
|
||||
cfg.Enabled = *req.Enabled
|
||||
}
|
||||
if req.Provider != nil {
|
||||
cfg.Provider = *req.Provider
|
||||
}
|
||||
if req.AccessKeyID != nil {
|
||||
cfg.AccessKeyID = *req.AccessKeyID
|
||||
}
|
||||
if req.AccessKeySecret != nil && *req.AccessKeySecret != "" {
|
||||
cfg.AccessKeySecret = *req.AccessKeySecret
|
||||
}
|
||||
if req.Endpoint != nil {
|
||||
cfg.Endpoint = *req.Endpoint
|
||||
}
|
||||
if req.SignName != nil {
|
||||
cfg.SignName = *req.SignName
|
||||
}
|
||||
if req.LoginTemplateCode != nil {
|
||||
cfg.LoginTemplateCode = *req.LoginTemplateCode
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package tenantsms
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
)
|
||||
|
||||
func TestRepositoryEncryptsSecretAndPreservesBlankUpdate(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.TenantSMSConfig{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db, &crypto.MockEncryptor{})
|
||||
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: 101})
|
||||
enabled := true
|
||||
provider := "aliyun"
|
||||
keyID := "test-key-id"
|
||||
secret := "test-secret"
|
||||
sign := "解忧商行"
|
||||
template := "SMS_123456"
|
||||
|
||||
item, err := repo.Update(ctx, 7, UpdateRequest{
|
||||
Enabled: &enabled,
|
||||
Provider: &provider,
|
||||
AccessKeyID: &keyID,
|
||||
AccessKeySecret: &secret,
|
||||
SignName: &sign,
|
||||
LoginTemplateCode: &template,
|
||||
}, auditlog.Meta{RequestID: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !item.Enabled || !item.HasSecret || item.MaskedSecret == secret {
|
||||
t.Fatalf("unexpected dto: %+v", item)
|
||||
}
|
||||
|
||||
cfg, err := repo.Get(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.AccessKeySecret != secret {
|
||||
t.Fatalf("secret = %q, want %q", cfg.AccessKeySecret, secret)
|
||||
}
|
||||
|
||||
newSign := "解忧商行新版"
|
||||
if _, err := repo.Update(ctx, 7, UpdateRequest{SignName: &newSign}, auditlog.Meta{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err = repo.Get(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.AccessKeySecret != secret || cfg.SignName != newSign {
|
||||
t.Fatalf("update lost secret or sign: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepositoryRejectsIncompleteEnabledConfig(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.TenantSMSConfig{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewRepository(db, &crypto.MockEncryptor{})
|
||||
ctx := tenancy.WithScope(t.Context(), tenancy.Scope{TenantID: 202})
|
||||
enabled := true
|
||||
if _, err := repo.Update(ctx, 7, UpdateRequest{Enabled: &enabled}, auditlog.Meta{}); err == nil {
|
||||
t.Fatal("enabled config without credentials must fail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package tenantsms
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
smsprovider "hfb_sys/backend/internal/integrations/sms"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type cachedProvider struct {
|
||||
provider smsprovider.Provider
|
||||
fingerprint string
|
||||
}
|
||||
|
||||
type Resolver struct {
|
||||
repo *Repository
|
||||
logger *zap.Logger
|
||||
mu sync.RWMutex
|
||||
entries map[uint64]cachedProvider
|
||||
}
|
||||
|
||||
func NewResolver(repo *Repository, logger *zap.Logger) *Resolver {
|
||||
return &Resolver{repo: repo, logger: logger, entries: make(map[uint64]cachedProvider)}
|
||||
}
|
||||
|
||||
func (r *Resolver) ResolveSMSProvider(ctx context.Context) (smsprovider.Provider, error) {
|
||||
if r == nil || r.repo == nil {
|
||||
return nil, nil
|
||||
}
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
if tenantID == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
cfg, err := r.repo.Get(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !cfg.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
fingerprint := configFingerprint(cfg)
|
||||
r.mu.RLock()
|
||||
cached := r.entries[tenantID]
|
||||
r.mu.RUnlock()
|
||||
if cached.provider != nil && cached.fingerprint == fingerprint {
|
||||
return cached.provider, nil
|
||||
}
|
||||
provider, err := smsprovider.NewAliyunProvider(smsprovider.AliyunConfig{
|
||||
AccessKeyID: cfg.AccessKeyID,
|
||||
AccessKeySecret: cfg.AccessKeySecret,
|
||||
Endpoint: cfg.Endpoint,
|
||||
SignName: cfg.SignName,
|
||||
LoginTemplateCode: cfg.LoginTemplateCode,
|
||||
}, r.logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.entries[tenantID] = cachedProvider{provider: provider, fingerprint: fingerprint}
|
||||
r.mu.Unlock()
|
||||
return provider, nil
|
||||
}
|
||||
|
||||
func configFingerprint(cfg Config) string {
|
||||
sum := sha256.Sum256([]byte(strings.Join([]string{
|
||||
cfg.Provider,
|
||||
cfg.AccessKeyID,
|
||||
cfg.AccessKeySecret,
|
||||
cfg.Endpoint,
|
||||
cfg.SignName,
|
||||
cfg.LoginTemplateCode,
|
||||
}, "|")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import (
|
||||
"hfb_sys/backend/internal/modules/realname"
|
||||
"hfb_sys/backend/internal/modules/supportgroup"
|
||||
"hfb_sys/backend/internal/modules/systemconfig"
|
||||
"hfb_sys/backend/internal/modules/tenantsms"
|
||||
"hfb_sys/backend/internal/modules/user"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/internal/modules/withdrawal"
|
||||
@@ -100,6 +101,12 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
}
|
||||
smsProvider := NewSMSProvider(cfg, logger)
|
||||
authService := auth.NewService(userRepo, deps.Redis, jwtManager, smsProvider, logger)
|
||||
var tenantSMSHandler *tenantsms.Handler
|
||||
if deps.DB != nil {
|
||||
tenantSMSRepo := tenantsms.NewRepository(deps.DB, fieldEncryptor)
|
||||
authService.SetTenantSMSResolver(tenantsms.NewResolver(tenantSMSRepo, logger))
|
||||
tenantSMSHandler = tenantsms.NewHandler(tenantSMSRepo)
|
||||
}
|
||||
authHandler := auth.NewHandler(authService)
|
||||
var adminAuthRepo *adminauth.Repository
|
||||
if deps.DB != nil {
|
||||
@@ -983,6 +990,10 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine {
|
||||
|
||||
adminRoutes.GET("/system-configs", requirePerm("system_config:view"), systemConfigHandler.List)
|
||||
adminRoutes.PUT("/system-configs/:key", requirePerm("system_config:update"), systemConfigHandler.Update)
|
||||
if tenantSMSHandler != nil {
|
||||
adminRoutes.GET("/tenant-sms-config", requirePerm("system_config:view"), tenantSMSHandler.Get)
|
||||
adminRoutes.PUT("/tenant-sms-config", requirePerm("system_config:update"), tenantSMSHandler.Update)
|
||||
}
|
||||
adminRoutes.GET("/backups/status", requirePerm("backup:view"), backupMonitorHandler.Status)
|
||||
adminRoutes.GET("/backups/schedule", requirePerm("backup:view"), systemConfigHandler.BackupSchedule)
|
||||
adminRoutes.PUT("/backups/schedule", requirePerm("backup:schedule:update"), systemConfigHandler.UpdateBackupSchedule)
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE tenant_sms_configs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
tenant_id BIGINT UNSIGNED NOT NULL,
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||
provider VARCHAR(32) NOT NULL DEFAULT 'aliyun',
|
||||
access_key_id VARCHAR(128) NOT NULL DEFAULT '',
|
||||
access_key_secret VARCHAR(1024) NOT NULL DEFAULT '',
|
||||
endpoint VARCHAR(255) NOT NULL DEFAULT 'dysmsapi.aliyuncs.com',
|
||||
sign_name VARCHAR(64) NOT NULL DEFAULT '',
|
||||
login_template_code VARCHAR(64) NOT NULL DEFAULT '',
|
||||
updated_by BIGINT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_tenant_sms_configs_tenant (tenant_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经营租户登录短信配置';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS tenant_sms_configs;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { apiClient } from '@/shared/api/client'
|
||||
import type { ApiResponse } from '@/shared/types/types'
|
||||
|
||||
export interface TenantSMSConfig {
|
||||
enabled: boolean
|
||||
provider: string
|
||||
access_key_id: string
|
||||
masked_secret: string
|
||||
has_secret: boolean
|
||||
endpoint: string
|
||||
sign_name: string
|
||||
login_template_code: string
|
||||
}
|
||||
|
||||
export interface UpdateTenantSMSConfigPayload {
|
||||
enabled: boolean
|
||||
provider: string
|
||||
access_key_id: string
|
||||
access_key_secret?: string
|
||||
endpoint: string
|
||||
sign_name: string
|
||||
login_template_code: string
|
||||
}
|
||||
|
||||
export async function fetchTenantSMSConfig() {
|
||||
const { data } =
|
||||
await apiClient.get<ApiResponse<TenantSMSConfig>>('/admin/tenant-sms-config')
|
||||
return data.data
|
||||
}
|
||||
|
||||
export async function updateTenantSMSConfig(payload: UpdateTenantSMSConfigPayload) {
|
||||
const { data } = await apiClient.put<ApiResponse<TenantSMSConfig>>(
|
||||
'/admin/tenant-sms-config',
|
||||
payload
|
||||
)
|
||||
return data.data
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<script setup lang="ts">
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
import {
|
||||
updateTenantSMSConfig,
|
||||
type TenantSMSConfig,
|
||||
type UpdateTenantSMSConfigPayload,
|
||||
} from '@/features/admin/api/tenantSmsConfig'
|
||||
import { readError } from '@/shared/utils/error'
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean
|
||||
config: TenantSMSConfig
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'update:modelValue', value: boolean): void
|
||||
(event: 'saved'): void
|
||||
}>()
|
||||
|
||||
const submitting = ref(false)
|
||||
const secretInput = ref('')
|
||||
const form = ref<UpdateTenantSMSConfigPayload>({
|
||||
enabled: false,
|
||||
provider: 'aliyun',
|
||||
access_key_id: '',
|
||||
endpoint: 'dysmsapi.aliyuncs.com',
|
||||
sign_name: '',
|
||||
login_template_code: '',
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [props.modelValue, props.config] as const,
|
||||
([visible]) => {
|
||||
if (!visible) return
|
||||
secretInput.value = ''
|
||||
form.value = {
|
||||
enabled: props.config.enabled,
|
||||
provider: props.config.provider || 'aliyun',
|
||||
access_key_id: props.config.access_key_id || '',
|
||||
endpoint: props.config.endpoint || 'dysmsapi.aliyuncs.com',
|
||||
sign_name: props.config.sign_name || '',
|
||||
login_template_code: props.config.login_template_code || '',
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
async function handleSave() {
|
||||
if (form.value.enabled) {
|
||||
if (!form.value.access_key_id.trim()) {
|
||||
ElMessage.warning('启用独立短信时,AccessKey ID 不能为空')
|
||||
return
|
||||
}
|
||||
if (!props.config.has_secret && !secretInput.value.trim()) {
|
||||
ElMessage.warning('启用独立短信时,AccessKey Secret 不能为空')
|
||||
return
|
||||
}
|
||||
if (!form.value.sign_name.trim()) {
|
||||
ElMessage.warning('启用独立短信时,短信签名不能为空')
|
||||
return
|
||||
}
|
||||
if (!form.value.login_template_code.trim()) {
|
||||
ElMessage.warning('启用独立短信时,登录验证码模板 Code 不能为空')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
submitting.value = true
|
||||
try {
|
||||
const payload: UpdateTenantSMSConfigPayload = {
|
||||
...form.value,
|
||||
access_key_id: form.value.access_key_id.trim(),
|
||||
endpoint: form.value.endpoint.trim() || 'dysmsapi.aliyuncs.com',
|
||||
sign_name: form.value.sign_name.trim(),
|
||||
login_template_code: form.value.login_template_code.trim(),
|
||||
}
|
||||
if (secretInput.value.trim()) {
|
||||
payload.access_key_secret = secretInput.value.trim()
|
||||
}
|
||||
await updateTenantSMSConfig(payload)
|
||||
ElMessage.success('本站登录短信配置已保存')
|
||||
emit('saved')
|
||||
emit('update:modelValue', false)
|
||||
} catch (error) {
|
||||
ElMessage.error(readError(error, '登录短信配置保存失败'))
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
title="本站登录短信配置"
|
||||
width="680px"
|
||||
destroy-on-close
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<div class="tenant-sms-form">
|
||||
<el-alert
|
||||
type="info"
|
||||
:closable="false"
|
||||
show-icon
|
||||
title="开启后,本站登录和注册验证码使用这里配置的阿里云短信额度与签名;关闭后回退主站默认短信通道。"
|
||||
/>
|
||||
<el-form label-position="top">
|
||||
<el-form-item label="启用本站独立登录短信">
|
||||
<el-switch v-model="form.enabled" active-text="启用" inactive-text="回退主站" />
|
||||
</el-form-item>
|
||||
<div class="form-grid">
|
||||
<el-form-item label="短信服务商">
|
||||
<el-input v-model="form.provider" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item label="API Endpoint">
|
||||
<el-input v-model="form.endpoint" placeholder="dysmsapi.aliyuncs.com" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<el-form-item label="AccessKey ID" :required="form.enabled">
|
||||
<el-input v-model="form.access_key_id" autocomplete="off" />
|
||||
</el-form-item>
|
||||
<el-form-item label="AccessKey Secret" :required="form.enabled && !config.has_secret">
|
||||
<el-input
|
||||
v-model="secretInput"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
show-password
|
||||
:placeholder="config.has_secret ? `已保存 ${config.masked_secret},留空保持不变` : '请输入 AccessKey Secret'"
|
||||
/>
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="form-grid">
|
||||
<el-form-item label="短信签名" :required="form.enabled">
|
||||
<el-input v-model="form.sign_name" placeholder="例如:解忧商行" />
|
||||
</el-form-item>
|
||||
<el-form-item label="登录验证码模板 Code" :required="form.enabled">
|
||||
<el-input v-model="form.login_template_code" placeholder="例如:SMS_123456789" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
</el-form>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<el-button :disabled="submitting" @click="emit('update:modelValue', false)">取消</el-button>
|
||||
<el-button type="primary" :loading="submitting" @click="handleSave">保存配置</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.tenant-sms-form {
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.form-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -22,6 +22,10 @@ import {
|
||||
updateSystemConfig,
|
||||
type SystemConfig,
|
||||
} from '@/features/admin/api/systemConfigs'
|
||||
import {
|
||||
fetchTenantSMSConfig,
|
||||
type TenantSMSConfig,
|
||||
} from '@/features/admin/api/tenantSmsConfig'
|
||||
import { parseRenterGrowthConfig } from '@/features/admin/api/renterGrowth'
|
||||
import {
|
||||
parseSmsBusinessTemplatesConfig,
|
||||
@@ -51,6 +55,7 @@ import PostRentalNoticeDialog from '../components/PostRentalNoticeDialog.vue'
|
||||
import GeneralConfigDialog from '../components/GeneralConfigDialog.vue'
|
||||
import RenterGrowthConfigDialog from '../components/RenterGrowthConfigDialog.vue'
|
||||
import SmsNodeTemplatesDialog from '../components/SmsNodeTemplatesDialog.vue'
|
||||
import TenantSmsConfigDialog from '../components/TenantSmsConfigDialog.vue'
|
||||
import QualityOwnerConfigDialog from '../components/QualityOwnerConfigDialog.vue'
|
||||
import AutoWelcomeConfig from '../components/AutoWelcomeConfig.vue'
|
||||
import {
|
||||
@@ -100,6 +105,8 @@ const postRentalNoticeVisible = ref(false)
|
||||
const generalVisible = ref(false)
|
||||
const renterGrowthVisible = ref(false)
|
||||
const smsNodeTemplatesVisible = ref(false)
|
||||
const tenantSMSConfig = ref<TenantSMSConfig | null>(null)
|
||||
const tenantSMSVisible = ref(false)
|
||||
|
||||
const publishConfig = computed(
|
||||
() => configs.value.find(item => item.key === 'listing.publish_options') || null
|
||||
@@ -318,7 +325,9 @@ onMounted(loadConfigs)
|
||||
async function loadConfigs() {
|
||||
loading.value = true
|
||||
try {
|
||||
configs.value = await fetchSystemConfigs()
|
||||
const [items, smsConfig] = await Promise.all([fetchSystemConfigs(), fetchTenantSMSConfig()])
|
||||
configs.value = items
|
||||
tenantSMSConfig.value = smsConfig
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -715,6 +724,41 @@ function formatConfigValue(row: SystemConfig) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="tenantSMSConfig" class="publish-config-panel">
|
||||
<div class="publish-config-main">
|
||||
<div>
|
||||
<p class="eyebrow">Login SMS</p>
|
||||
<h2>本站登录短信通道</h2>
|
||||
<span
|
||||
>大锤商行和解忧商行各自独立配置登录验证码短信。未启用时回退主站通道;启用后使用本站自己的阿里云额度与短信签名。</span
|
||||
>
|
||||
</div>
|
||||
<el-button type="primary" @click="tenantSMSVisible = true">编辑登录短信</el-button>
|
||||
</div>
|
||||
<div class="publish-stat-grid home-stat-grid">
|
||||
<div class="publish-stat">
|
||||
<strong>{{ tenantSMSConfig.enabled ? '已启用' : '未启用' }}</strong>
|
||||
<span>当前站点</span>
|
||||
</div>
|
||||
<div class="publish-stat">
|
||||
<strong>{{ tenantSMSConfig.enabled ? '独立通道' : '主站通道' }}</strong>
|
||||
<span>发送来源</span>
|
||||
</div>
|
||||
<div class="publish-stat">
|
||||
<strong>{{ tenantSMSConfig.sign_name || '未配置' }}</strong>
|
||||
<span>短信签名</span>
|
||||
</div>
|
||||
<div class="publish-stat">
|
||||
<strong>{{ tenantSMSConfig.login_template_code || '未配置' }}</strong>
|
||||
<span>登录模板</span>
|
||||
</div>
|
||||
<div class="publish-stat">
|
||||
<strong>{{ tenantSMSConfig.has_secret ? '已保存' : '未保存' }}</strong>
|
||||
<span>AccessKey Secret</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="smsNodeTemplatesConfig" class="publish-config-panel">
|
||||
<div class="publish-config-main">
|
||||
<div>
|
||||
@@ -1144,6 +1188,13 @@ function formatConfigValue(row: SystemConfig) {
|
||||
@saved="loadConfigs"
|
||||
/>
|
||||
|
||||
<TenantSmsConfigDialog
|
||||
v-if="tenantSMSConfig"
|
||||
v-model="tenantSMSVisible"
|
||||
:config="tenantSMSConfig"
|
||||
@saved="loadConfigs"
|
||||
/>
|
||||
|
||||
<GeneralConfigDialog
|
||||
v-if="currentEditingConfig"
|
||||
v-model="generalVisible"
|
||||
|
||||
@@ -66,6 +66,12 @@ export const AUDIT_ACTION_OPTIONS: AuditOption[] = [
|
||||
// 系统配置
|
||||
{ value: 'system_config.create', label: '创建系统配置', group: '系统配置', highRisk: true },
|
||||
{ value: 'system_config.update', label: '更新系统配置', group: '系统配置', highRisk: true },
|
||||
{
|
||||
value: 'tenant_sms_config.update',
|
||||
label: '更新本站登录短信配置',
|
||||
group: '系统配置',
|
||||
highRisk: true,
|
||||
},
|
||||
// 支付配置
|
||||
{ value: 'payment_config.create', label: '创建支付配置', group: '支付配置', highRisk: true },
|
||||
{ value: 'payment_config.update', label: '更新支付配置', group: '支付配置', highRisk: true },
|
||||
|
||||
Reference in New Issue
Block a user