31 lines
739 B
Go
31 lines
739 B
Go
package middlewares
|
|
|
|
import (
|
|
"gauth-central/internal/services"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func AuthMiddleware(jwtService *services.JWTService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is required"})
|
|
return
|
|
}
|
|
|
|
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
|
|
claims, err := jwtService.ValidateToken(tokenString)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token: " + err.Error()})
|
|
return
|
|
}
|
|
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("email", claims.Email)
|
|
c.Next()
|
|
}
|
|
}
|