shelfy-v2/internal/middlewares/checkAuth.go
2025-07-27 16:26:30 +02:00

78 lines
2.4 KiB
Go
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middlewares
import (
"canguidev/shelfy/internal/models"
"fmt"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
"gorm.io/gorm"
)
func CheckAuth(db *gorm.DB) gin.HandlerFunc {
return func(c *gin.Context) {
// 1. Récupère le token (header ou query string)
authHeader := c.GetHeader("Authorization")
var tokenString string
if authHeader != "" {
// Mode classique : Authorization: Bearer xxxxx
authToken := strings.Split(authHeader, " ")
if len(authToken) != 2 || authToken[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
c.AbortWithStatus(http.StatusUnauthorized)
return
}
tokenString = authToken[1]
} else {
// Mode web: token dans lURL
tokenString = c.Query("token")
if tokenString == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header is missing"})
c.AbortWithStatus(http.StatusUnauthorized)
return
}
}
// 2. Vérifie et parse le JWT
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte("SECRET"), nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
c.AbortWithStatus(http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
if float64(time.Now().Unix()) > claims["exp"].(float64) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "token expired"})
c.AbortWithStatus(http.StatusUnauthorized)
return
}
var user models.User
var id = claims["id"]
result := db.First(&user, id)
if result.RowsAffected == 0 {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set("currentUser", user)
c.Next()
}
}