84 lines
2.2 KiB
Go
84 lines
2.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"gestion/db"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// BlockClientIfPenalty bloque le checkout si le client a une amende non payée.
|
|
// Lit d'abord les paramètres globaux (penalties_enabled), puis le PenaltyCache Redis, fallback DB.
|
|
func BlockClientIfPenalty(c *gin.Context) {
|
|
database := c.MustGet("database").(*db.Database)
|
|
|
|
// Vérifier si les amendes sont activées dans les paramètres globaux
|
|
if settings, err := database.GetSettings(); err == nil && !settings.PenaltiesEnabled {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
clientID, exists := c.Get("client_id")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentification requise"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 1. Tenter le cache Redis via la session
|
|
if id, ok := clientID.(int); ok {
|
|
if session, err := database.GetClientSession(id); err == nil {
|
|
if session.PenaltyCache > 0 {
|
|
log.Printf("🚫 [PENALTY] Checkout bloqué pour client_id=%d (amende=%.2f via cache)", id, session.PenaltyCache)
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"error": "Commande bloquée : vous avez une amende en attente de paiement",
|
|
"amende": session.PenaltyCache,
|
|
"blocked": true,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
// Cache présent et amende = 0 → on laisse passer sans requête DB
|
|
c.Next()
|
|
return
|
|
}
|
|
}
|
|
|
|
// 2. Fallback DB si session Redis absente/expirée
|
|
username, exists := c.Get("username")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authentification requise"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
usernameStr, ok := username.(string)
|
|
if !ok || usernameStr == "" {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "Username invalide"})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
amende, err := database.GetClientAmende(usernameStr)
|
|
if err != nil {
|
|
log.Printf("❌ [PENALTY] Erreur vérification amende pour %s: %v", usernameStr, err)
|
|
// En cas d'erreur DB on laisse passer pour ne pas bloquer l'utilisateur injustement
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
if amende > 0 {
|
|
log.Printf("🚫 [PENALTY] Checkout bloqué pour %s (amende=%.2f via DB)", usernameStr, amende)
|
|
c.JSON(http.StatusForbidden, gin.H{
|
|
"error": "Commande bloquée : vous avez une amende en attente de paiement",
|
|
"amende": amende,
|
|
"blocked": true,
|
|
})
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Next()
|
|
}
|