feat: add login authentication and certificate expiry notifications

- JWT-based login with ADMIN_USER/ADMIN_PASSWORD env config
- Login page with auth guard for Vue frontend
- Feishu bot webhook notification for expiring certificates
- SMTP email notification for expiring certificates
- Daily 8:00 AM cron for expiry checks
- Startup health check notification
This commit is contained in:
2026-07-23 16:25:02 +08:00
parent 1bb895fd67
commit 2d70a15307
17 changed files with 2813 additions and 66 deletions
+152 -8
View File
@@ -1,9 +1,12 @@
package main
import (
"auto-ssl/auth"
"auto-ssl/config"
"auto-ssl/handlers"
"auto-ssl/notify"
"auto-ssl/services"
"fmt"
"log"
"net/http"
"os"
@@ -39,8 +42,15 @@ func main() {
r.StaticFile("/favicon.svg", "./dist/favicon.svg")
r.StaticFile("/", "./dist/index.html")
// API routes
// Public routes (no auth required)
r.POST("/api/login", handleLogin)
r.GET("/api/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
// API routes with auth
api := r.Group("/api")
api.Use(authMiddleware())
{
certHandler := handlers.NewCertHandler(cfg)
@@ -60,12 +70,12 @@ func main() {
r.NoRoute(func(c *gin.Context) {
// 静态资源请求直接返回404,避免返回html导致MIME类型错误
if strings.HasPrefix(c.Request.URL.Path, "/assets/") ||
strings.HasSuffix(c.Request.URL.Path, ".js") ||
strings.HasSuffix(c.Request.URL.Path, ".css") ||
strings.HasSuffix(c.Request.URL.Path, ".png") ||
strings.HasSuffix(c.Request.URL.Path, ".svg") ||
strings.HasSuffix(c.Request.URL.Path, ".ico") {
if strings.HasPrefix(c.Request.URL.Path, "/assets/") ||
strings.HasSuffix(c.Request.URL.Path, ".js") ||
strings.HasSuffix(c.Request.URL.Path, ".css") ||
strings.HasSuffix(c.Request.URL.Path, ".png") ||
strings.HasSuffix(c.Request.URL.Path, ".svg") ||
strings.HasSuffix(c.Request.URL.Path, ".ico") {
c.AbortWithStatus(http.StatusNotFound)
return
}
@@ -73,8 +83,10 @@ func main() {
c.File("./dist/index.html")
})
// Setup cron for auto-renewal (runs daily at 3:00 AM)
// Setup cron scheduler
c := cron.New()
// Daily renewal check at 3:00 AM
c.AddFunc("0 3 * * *", func() {
log.Println("Running scheduled certificate renewal check...")
certs := config.Store.GetActiveWithAutoRenew()
@@ -93,6 +105,17 @@ func main() {
}
}
})
// Certificate expiry notification check at 8:00 AM daily
c.AddFunc("0 8 * * *", func() {
notifyCfg := notify.LoadNotifyConfig()
if !notifyCfg.IsConfigured() {
log.Println("Notification not configured, skipping expiry check notification")
return
}
runExpiryNotification(notifyCfg)
})
c.Start()
// Set ACME HTTP-01 challenge port from env (default 8082)
@@ -109,3 +132,124 @@ func main() {
log.Fatalf("Failed to start server: %v", err)
}
}
// handleLogin authenticates user and returns JWT token
func handleLogin(c *gin.Context) {
var req auth.LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请输入用户名和密码"})
return
}
if !auth.Authenticate(req.Username, req.Password) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
return
}
token, expiresAt, err := auth.GenerateToken(req.Username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "生成token失败"})
return
}
c.JSON(http.StatusOK, auth.LoginResponse{
Token: token,
Username: req.Username,
ExpiresAt: expiresAt,
})
}
// authMiddleware validates JWT token on protected routes
func authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
// Also check query param (for websocket / event-stream compatibility)
authHeader = c.Query("token")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未授权,请先登录"})
return
}
// Validate as-is (query param is the raw token)
claims, err := auth.ValidateToken(authHeader)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token已过期或无效"})
return
}
c.Set("username", claims.Username)
c.Next()
return
}
// Extract Bearer token
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
tokenString = authHeader
}
claims, err := auth.ValidateToken(tokenString)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "token已过期或无效"})
return
}
c.Set("username", claims.Username)
c.Next()
}
}
// runExpiryNotification checks all certificates and sends notifications for expiring ones
func runExpiryNotification(notifyCfg *notify.Config) {
certs := config.Store.GetAll()
var expiringCerts []notify.CertInfo
for _, cert := range certs {
if cert.Status != "active" || cert.ExpiresAt == nil {
continue
}
daysLeft := int(time.Until(*cert.ExpiresAt).Hours() / 24)
// Notify if within 30 days of expiry (or already expired)
if daysLeft <= 30 {
info := notify.CertInfo{
Domain: cert.Domain,
Status: cert.Status,
ExpiresAt: cert.ExpiresAt,
DaysLeft: daysLeft,
}
if daysLeft < 0 {
info.Status = "expired"
}
expiringCerts = append(expiringCerts, info)
}
}
if len(expiringCerts) > 0 {
log.Printf("Found %d expiring certificates, sending notifications", len(expiringCerts))
if err := notifyCfg.NotifyCertExpiring(expiringCerts); err != nil {
log.Printf("Failed to send expiry notifications: %v", err)
}
} else {
log.Println("No expiring certificates found, skipping notification")
}
}
func init() {
// Check if notification is configured and run once at startup
time.AfterFunc(10*time.Second, func() {
notifyCfg := notify.LoadNotifyConfig()
if notifyCfg.IsConfigured() {
log.Println("Running startup certificate expiry check...")
runExpiryNotification(notifyCfg)
}
})
// Validate ADMIN_USER / ADMIN_PASSWORD env setting
adminUser := os.Getenv("ADMIN_USER")
adminPass := os.Getenv("ADMIN_PASSWORD")
if adminUser != "" || adminPass != "" {
log.Printf("Admin credentials configured via environment (user: %s)", adminUser)
}
_ = fmt.Sprintf // import usage, prevent unused import error
}