78 lines
2.4 KiB
Go
78 lines
2.4 KiB
Go
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 l’URL
|
||
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()
|
||
}
|
||
}
|
||
|