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