101 lines
2.5 KiB
Go
101 lines
2.5 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"hightube/internal/db"
|
|
"hightube/internal/model"
|
|
"hightube/internal/monitor"
|
|
"hightube/internal/utils"
|
|
)
|
|
|
|
// AuthMiddleware intercepts requests, validates JWT, and injects user_id into context
|
|
func AuthMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
parts := strings.Split(authHeader, " ")
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer {token}"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
tokenStr := parts[1]
|
|
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(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) {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
|
|
|
|
if c.Request.Method == "OPTIONS" {
|
|
c.AbortWithStatus(204)
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|