feat(notification): 增加邮件通知设置在线测试与保存门禁功能

This commit is contained in:
xuans committed 2026-10-17 18:40:49 +08:00
1 parent 72af7caee8
commit b7a99cc996
10 files changed
+470 -16

No files matched your search

@@ -0,0 +1,123 @@
package httpapi
import (
"context"
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"git.pcux.cn/xuans/Scert/backend/internal/notification"
)
type notificationTestRequest struct {
SMTPEnabled bool `json:"smtp_enabled"`
SMTPHost string `json:"smtp_host"`
SMTPPort int `json:"smtp_port"`
SMTPUsername string `json:"smtp_username"`
SMTPPassword string `json:"smtp_password"`
SMTPMode string `json:"smtp_mode"`
SMTPAllowPlaintextAuth bool `json:"smtp_allow_plaintext_auth"`
Recipient string `json:"recipient"`
HTTPEnabled bool `json:"http_enabled"`
HTTPCredentials map[string]string `json:"http_credentials"`
Provider string `json:"provider"`
Endpoint string `json:"endpoint"`
HTTPPath string `json:"http_path"`
HTTPLoginPath string `json:"http_login_path"`
HTTPAuthMode string `json:"http_auth_mode"`
}
type memoryCredentialReader struct {
creds map[string]map[string]string
}
func (m *memoryCredentialReader) Get(ctx context.Context, ref string) (map[string]string, error) {
if m == nil || m.creds == nil {
return nil, errors.New("凭据不存在")
}
val, ok := m.creds[ref]
if !ok {
return nil, errors.New("凭据不存在")
}
return val, nil
}
func (s *Server) testNotification(c *gin.Context) {
_, authenticated := s.currentAuthSession(c)
if !authenticated {
s.writeError(c, http.StatusUnauthorized, "请先登录管理后台", nil)
return
}
var req notificationTestRequest
if err := bindJSON(c, &req, jsonRequestBodyLimit); err != nil {
s.writeError(c, http.StatusBadRequest, "测试请求参数无效", err)
return
}
targetRecipient := strings.TrimSpace(req.Recipient)
if targetRecipient == "" {
s.writeError(c, http.StatusBadRequest, "请输入测试收件人邮箱", nil)
return
}
s.configMu.RLock()
currentCfg := s.config.Notification
s.configMu.RUnlock()
testCfg := currentCfg
testCfg.SMTPEnabled = req.SMTPEnabled
if req.SMTPHost != "" {
testCfg.SMTPHost = strings.TrimSpace(req.SMTPHost)
}
if req.SMTPPort > 0 {
testCfg.SMTPPort = req.SMTPPort
}
if req.SMTPUsername != "" {
testCfg.SMTPUsername = strings.TrimSpace(req.SMTPUsername)
}
if req.SMTPMode != "" {
testCfg.SMTPMode = strings.TrimSpace(req.SMTPMode)
}
testCfg.SMTPAllowPlaintextAuth = req.SMTPAllowPlaintextAuth
credsMap := make(map[string]map[string]string)
smtpPassword := strings.TrimSpace(req.SMTPPassword)
if smtpPassword != "" {
testRef := "secret://test/smtp"
testCfg.SMTPCredentialRef = testRef
credsMap[testRef] = map[string]string{
"username": testCfg.SMTPUsername,
"password": smtpPassword,
}
} else if testCfg.SMTPCredentialRef != "" {
if reader, ok := s.secrets.(readinessSecretReader); ok && reader != nil {
if realCreds, err := reader.Get(c.Request.Context(), testCfg.SMTPCredentialRef); err == nil && realCreds != nil {
credsMap[testCfg.SMTPCredentialRef] = realCreds
}
}
}
if testCfg.SMTPEnabled && credsMap[testCfg.SMTPCredentialRef] == nil && testCfg.UsesSmailSystemAccount() {
s.writeError(c, http.StatusBadRequest, "尚未配置 SMTP 密码,请先输入密码再进行测试", nil)
return
}
reader := &memoryCredentialReader{creds: credsMap}
notifService := notification.New(testCfg, reader)
testCtx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
defer cancel()
if err := notifService.SendTestMail(testCtx, targetRecipient); err != nil {
s.writeError(c, http.StatusUnprocessableEntity, "邮件测试发送失败:"+err.Error(), err)
return
}
c.JSON(http.StatusOK, gin.H{
"message": "测试邮件已发送,请检查收件箱",
"recipient": targetRecipient,
})
}
@@ -0,0 +1,38 @@
package httpapi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.pcux.cn/xuans/Scert/backend/internal/repository"
)
func TestNotificationTestEndpointRequiresSuperAdmin(t *testing.T) {
f := newProjectMemberAPIFixture(t)
body := `{"recipient":"test@example.com","smtp_enabled":true}`
// 未登录
req := httptest.NewRequest(http.MethodPost, "/api/v1/notification/test", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
f.server.Handler().ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("expected 401 unauthorized, got %d", w.Code)
}
// 普通管理员(无系统设置权限)
adminCookie := httpUserSessionCookie(f.server, "admin-user", repository.UserRoleAdmin)
adminResp := serveUserRequest(f.server, adminCookie, http.MethodPost, "/api/v1/notification/test", body)
if adminResp.Code != http.StatusForbidden {
t.Fatalf("expected 403 forbidden for admin, got %d", adminResp.Code)
}
// 超级管理员,缺少收件人参数
superCookie := httpUserSessionCookie(f.server, "super-user", repository.UserRoleSuperAdmin)
invalidResp := serveUserRequest(f.server, superCookie, http.MethodPost, "/api/v1/notification/test", `{}`)
if invalidResp.Code != http.StatusBadRequest {
t.Fatalf("expected 400 bad request for empty recipient, got %d", invalidResp.Code)
}
}
+3 -1
View File
@@ -1,4 +1,4 @@
package httpapi
package httpapi
import (
"context"
@@ -253,6 +253,7 @@ func (s *Server) registerRoutes() {
s.router.GET("/api/v1/settings", privateProjectResponse, s.requireSuperAdminSystemConfig, s.getSettings)
s.router.PUT("/api/v1/settings", privateProjectResponse, s.requireSuperAdminSystemConfig, s.updateSettings)
adminAPI.POST("/dns/test", s.requireSuperAdminSystemConfig, s.dnsOperation, s.testAdminDNS)
adminAPI.POST("/notification/test", s.requireSuperAdminSystemConfig, s.testNotification)
adminAPI.POST("/dns/aliyun/check", s.requireSuperAdminSystemConfig, s.dnsOperation, s.checkAliyunDNSDomain)
adminAPI.POST("/renewal/run", s.requireSuperAdmin, s.runRenewalNow)
domainAPI.POST("/domains/:id/certificate/import", s.longOperation(certificateTaskTimeout), s.importCertificateFiles)
@@ -1108,3 +1109,4 @@ func (s *Server) recordServerHostKeyAudit(c *gin.Context, action, serverID strin
s.logger.Warn("保存服务器主机指纹审计日志失败", "server_id", serverID, "error", err)
}
}
@@ -0,0 +1,96 @@
package notification
import (
"context"
"errors"
"fmt"
"net/mail"
"strings"
"time"
)
// SendTestMail 发送测试邮件,验证发信通道配置与网络连通性。
func (s *Service) SendTestMail(ctx context.Context, targetRecipient string) error {
if s == nil || (!s.config.HTTPEnabled && !s.config.SMTPEnabled) {
return errors.New("发信服务未启用或未正确配置")
}
targetRecipient = strings.TrimSpace(targetRecipient)
if targetRecipient == "" {
if len(s.config.Recipients) > 0 {
targetRecipient = s.config.Recipients[0]
}
}
if targetRecipient == "" {
return errors.New("收件人邮箱不能为空")
}
parsed, err := mail.ParseAddress(targetRecipient)
if err != nil || parsed.Address != targetRecipient {
return errors.New("测试邮件收件人地址格式无效")
}
fromName, from, err := s.config.SenderIdentity()
if err != nil {
return err
}
nowStr := time.Now().Format("2006-01-02 15:04:05")
hostInfo := s.config.SMTPHost
if s.config.SMTPPort > 0 {
hostInfo = fmt.Sprintf("%s:%d", hostInfo, s.config.SMTPPort)
}
text := fmt.Sprintf("Scert 邮件通知通道测试成功\n\n发信测试已完成,您的邮件通知配置有效且能正常送达。\n发信主机:%s\n发信账号:%s\n测试时间:%s\n\n此邮件为系统自动测试邮件,无需回复。",
hostInfo, s.config.SMTPUsername, nowStr)
var htmlBuilder strings.Builder
beginHTMLMail(&htmlBuilder, "邮件通道测试成功")
htmlBuilder.WriteString(`<div style="display:inline-block;padding:4px 12px;border-radius:999px;background:#16803c;color:#ffffff;font-size:13px;font-weight:700;">测试通过</div>`)
htmlBuilder.WriteString(`<h2 style="margin:14px 0 6px;font-size:24px;line-height:1.35;color:#18181b;">发信通道联通成功</h2>`)
htmlBuilder.WriteString(`<p style="margin:0 0 24px;color:#71717a;font-size:14px;">您的 Scert 邮件通知配置已通过在线发信验证,可正常发送通知邮件。</p>`)
htmlBuilder.WriteString(`<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:collapse;border:1px solid #e4e4e7;border-radius:8px;overflow:hidden;font-size:14px;">`)
writeHTMLField(&htmlBuilder, "SMTP 主机", hostInfo)
if s.config.SMTPUsername != "" {
writeHTMLField(&htmlBuilder, "发信账号", s.config.SMTPUsername)
}
writeHTMLField(&htmlBuilder, "连接模式", s.config.SMTPMode)
writeHTMLField(&htmlBuilder, "目标收件人", targetRecipient)
writeHTMLField(&htmlBuilder, "验证时间", nowStr)
htmlBuilder.WriteString(`</table>`)
htmlBuilder.WriteString(`<div style="margin-top:20px;padding:14px 16px;border-left:4px solid #16803c;border-radius:8px;background:#f0fdf4;color:#166534;font-size:13px;line-height:1.5;">系统已确认该发信通道有效,您可以放心保存当前系统邮件通知设置。</div>`)
endHTMLMail(&htmlBuilder)
payload := mailPayload{
From: address{Name: fromName, Email: from},
To: []address{{Email: targetRecipient}},
Subject: "[Scert] 邮件通知配置测试成功",
Text: text,
HTML: htmlBuilder.String(),
CC: []address{},
BCC: []address{},
Attrs: []any{},
}
if s.config.UsesSmailSystemAccount() {
if !s.config.SMTPEnabled {
return errors.New("Smail 系统通知账号必须启用 SMTP 通道")
}
if err := s.sendSMTPWithRetry(ctx, payload); err != nil {
return fmt.Errorf("SMTP 测试邮件发送失败:%w", err)
}
return nil
}
if s.config.HTTPEnabled {
if err := s.sendHTTPPayload(ctx, payload); err == nil {
return nil
}
}
if s.config.SMTPEnabled {
if err := s.sendSMTPWithRetry(ctx, payload); err != nil {
return fmt.Errorf("SMTP 测试邮件发送失败:%w", err)
}
return nil
}
return errors.New("测试邮件发送失败,请检查通道设置及网络连通性")
}