监控网页实现
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user