chore: build
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"gestion/db"
|
||||
"gestion/middleware"
|
||||
"gestion/models"
|
||||
"gestion/utils"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func cancelRateLimitKey(username string) string {
|
||||
return "cancel:" + username
|
||||
}
|
||||
|
||||
func ownAddressRateLimitKey(username string) string {
|
||||
return "update_own_addr:" + username
|
||||
}
|
||||
|
||||
// rateLimitedClients renvoie les usernames actuellement bloqués par l'un des
|
||||
// rate limits client : requêtes panier/commande (Redis), annulations et
|
||||
// modification d'adresse (mémoire). Un seul MGET pour toute la liste.
|
||||
func rateLimitedClients(clients []*models.Client) map[string]bool {
|
||||
limited := make(map[string]bool)
|
||||
if len(clients) == 0 {
|
||||
return limited
|
||||
}
|
||||
|
||||
keys := make([]string, len(clients))
|
||||
for i, cl := range clients {
|
||||
keys[i] = middleware.ClientRateLimitKey(cl.ID)
|
||||
}
|
||||
counts, err := db.Redis.MGet(db.RedisCtx, keys...).Result()
|
||||
if err != nil {
|
||||
log.Printf("⚠️ [RATELIMIT_STATUS] Erreur Redis: %v", err)
|
||||
}
|
||||
for i, v := range counts {
|
||||
s, ok := v.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(s); err == nil && n > middleware.ClientRateLimitMax {
|
||||
limited[clients[i].Username] = true
|
||||
}
|
||||
}
|
||||
|
||||
for _, cl := range clients {
|
||||
if isCancelRateLimited(cancelRateLimitKey(cl.Username)) || isRateLimited(ownAddressRateLimitKey(cl.Username)) {
|
||||
limited[cl.Username] = true
|
||||
}
|
||||
}
|
||||
return limited
|
||||
}
|
||||
|
||||
// ResetClientRateLimitAdmin lève tous les rate limits d'un client.
|
||||
// POST /api/v2/admin/protected/client/:username/ratelimit/reset
|
||||
func ResetClientRateLimitAdmin(c *gin.Context) {
|
||||
if c.GetString("role") != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux administrateurs"})
|
||||
return
|
||||
}
|
||||
|
||||
database := c.MustGet("database").(*db.Database)
|
||||
client, err := database.GetClientByUsername(c.Param("username"))
|
||||
if err != nil || client == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Client introuvable"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := db.Redis.Del(db.RedisCtx, middleware.ClientRateLimitKey(client.ID)).Err(); err != nil {
|
||||
utils.ServerErr(c, "Erreur levée du rate limit", err)
|
||||
return
|
||||
}
|
||||
resetCancelRateLimit(cancelRateLimitKey(client.Username))
|
||||
resetRateLimit(ownAddressRateLimitKey(client.Username))
|
||||
|
||||
log.Printf("✅ [RATELIMIT_RESET] Rate limit levé pour %s par %s", client.Username, c.GetString("username"))
|
||||
c.JSON(http.StatusOK, gin.H{"success": true, "message": "Rate limit levé"})
|
||||
}
|
||||
Reference in New Issue
Block a user