监控网页实现

This commit is contained in:
Z
2026-04-09 00:14:57 +08:00
parent 6b1c7242c7
commit 1cce5634b1
17 changed files with 1186 additions and 38 deletions

View File

@@ -7,6 +7,9 @@ import (
"github.com/gin-gonic/gin"
"hightube/internal/db"
"hightube/internal/model"
"hightube/internal/monitor"
"hightube/internal/utils"
)
@@ -28,19 +31,57 @@ func AuthMiddleware() gin.HandlerFunc {
}
tokenStr := parts[1]
userIDStr, err := utils.ParseToken(tokenStr)
claims, err := utils.ParseToken(tokenStr)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
c.Abort()
return
}
userID, _ := strconv.ParseUint(userIDStr, 10, 32)
userID, _ := strconv.ParseUint(claims.Subject, 10, 32)
var user model.User
if err := db.DB.First(&user, uint(userID)).Error; err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
c.Abort()
return
}
if !user.Enabled {
c.JSON(http.StatusForbidden, gin.H{"error": "Account is disabled"})
c.Abort()
return
}
c.Set("user_id", uint(userID))
c.Set("username", user.Username)
c.Set("role", user.Role)
c.Next()
}
}
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
role, ok := c.Get("role")
if !ok || role != "admin" {
c.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
c.Abort()
return
}
c.Next()
}
}
func RequestMetricsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
monitor.IncrementRequestCount()
c.Next()
if c.Writer.Status() >= http.StatusBadRequest {
monitor.IncrementErrorCount()
}
}
}
// CORSMiddleware handles cross-origin requests from web clients
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {