chore: build
Backend - Build & Lint / build (push) Successful in 31m59s
Frontend Admin - EAS Build / build (push) Successful in 1h32m56s

This commit is contained in:
Xor290
2026-11-01 13:08:58 +01:00
parent f3eaea4347
commit 0a18460f13
20 changed files with 1694 additions and 190 deletions
+73 -13
View File
@@ -511,7 +511,21 @@ func GetAllUsers(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
return
}
users, err := database.GetAllUsers()
limit := 100
offset := 0
if limitStr := c.Query("limit"); limitStr != "" {
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
limit = l
}
}
if offsetStr := c.Query("offset"); offsetStr != "" {
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
offset = o
}
}
users, total, err := database.GetAllUsers(limit, offset)
if err != nil {
log.Printf("❌ [GET_ALL_USERS] Erreur: %v", err)
@@ -528,11 +542,12 @@ func GetAllUsers(c *gin.Context) {
})
}
log.Printf("✅ [GET_ALL_USERS] %d users récupérés", len(sanitized))
log.Printf("✅ [GET_ALL_USERS] %d users récupérés (offset=%d, total=%d)", len(sanitized), offset, total)
c.JSON(http.StatusOK, gin.H{
"users": sanitized,
"count": len(sanitized),
"users": sanitized,
"count": total,
"has_more": int64(offset+len(users)) < total,
})
}
@@ -549,13 +564,39 @@ func GetAllDeliveryMen(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
return
}
usernames := make([]string, len(users))
for i, u := range users {
usernames[i] = u.Username
}
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
var sanitized []gin.H
for _, u := range users {
sanitized = append(sanitized, gin.H{
"id": u.ID,
"username": u.Username,
"role": u.Role,
})
det := detailsByUsername[u.Username]
if det == nil {
det = &db.DeliveryPersonDetails{Status: "offline"}
}
entry := gin.H{
"id": u.ID,
"username": u.Username,
"role": u.Role,
"status": det.Status,
"queue_size": det.QueueSize,
"total_deliveries": det.TotalDeliveries,
"completed_deliveries": det.CompletedDeliveries,
"pending_deliveries": det.PendingDeliveries,
}
if det.CurrentCommand != 0 {
entry["current_command"] = det.CurrentCommand
} else {
entry["current_command"] = nil
}
if det.HasLocation {
entry["location"] = gin.H{"latitude": det.Latitude, "longitude": det.Longitude}
} else {
entry["location"] = nil
}
sanitized = append(sanitized, entry)
}
log.Printf("✅ [GET_ALL_USERS] %d users récupérés", len(sanitized))
@@ -575,16 +616,33 @@ func GetAllClients(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "Accès réservé aux livreurs et aux administrateurs"})
return
}
clients, err := database.GetAllClients()
limit := 100
offset := 0
if limitStr := c.Query("limit"); limitStr != "" {
if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 {
limit = l
}
}
if offsetStr := c.Query("offset"); offsetStr != "" {
if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 {
offset = o
}
}
clients, total, err := database.GetAllClients(limit, offset)
if err != nil {
log.Printf("❌ [GET_ALL_CLIENTS] Erreur: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erreur récupération"})
return
}
limited := rateLimitedClients(clients)
var sanitized []gin.H
for _, cl := range clients {
sanitized = append(sanitized, gin.H{
"rate_limited": limited[cl.Username],
"id": cl.ID,
"username": cl.Username,
"nom": cl.Nom,
@@ -596,14 +654,16 @@ func GetAllClients(c *gin.Context) {
"cancellations_count": cl.CancellationsCount,
"last_penalty_reason": cl.LastPenaltyReason,
"referral_balance": cl.ReferralBalance,
"parrain": cl.Parrain,
})
}
log.Printf("✅ [GET_ALL_CLIENTS] %d clients récupérés", len(sanitized))
log.Printf("✅ [GET_ALL_CLIENTS] %d clients récupérés (offset=%d, total=%d)", len(sanitized), offset, total)
c.JSON(http.StatusOK, gin.H{
"clients": sanitized,
"count": len(sanitized),
"clients": sanitized,
"count": total,
"has_more": int64(offset+len(clients)) < total,
})
}
+17 -1
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
@@ -14,11 +15,26 @@ import (
var (
cancelRateLimitMap = make(map[string][]time.Time)
cancelRateLimitMu sync.Mutex
cancelMaxRequests = 5 // Max 5 annulations
cancelTimeWindow = time.Hour // Par heure
)
func isCancelRateLimited(key string) bool {
cancelRateLimitMu.Lock()
defer cancelRateLimitMu.Unlock()
return countRecent(cancelRateLimitMap[key], cancelTimeWindow) >= cancelMaxRequests
}
func resetCancelRateLimit(key string) {
cancelRateLimitMu.Lock()
defer cancelRateLimitMu.Unlock()
delete(cancelRateLimitMap, key)
}
func checkCancelRateLimit(key string) bool {
cancelRateLimitMu.Lock()
defer cancelRateLimitMu.Unlock()
now := time.Now()
if timestamps, exists := cancelRateLimitMap[key]; exists {
@@ -67,7 +83,7 @@ func CancelCommandByClient(c *gin.Context) {
return
}
rateLimitKey := fmt.Sprintf("cancel:%s", username)
rateLimitKey := cancelRateLimitKey(username)
if !checkCancelRateLimit(rateLimitKey) {
log.Printf("⚠️ [CANCEL_CLIENT] Rate limit dépassé pour %s", username)
c.JSON(http.StatusTooManyRequests, gin.H{
@@ -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é"})
}
+58 -1
View File
@@ -48,6 +48,30 @@ func checkRateLimit(key string) bool {
return true
}
// isRateLimited indique si la clé est actuellement bloquée, sans compter de requête.
func isRateLimited(key string) bool {
rateLimitMu.Lock()
defer rateLimitMu.Unlock()
return countRecent(rateLimitMap[key], timeWindow) >= maxRequests
}
func resetRateLimit(key string) {
rateLimitMu.Lock()
defer rateLimitMu.Unlock()
delete(rateLimitMap, key)
}
func countRecent(timestamps []time.Time, window time.Duration) int {
now := time.Now()
n := 0
for _, ts := range timestamps {
if now.Sub(ts) < window {
n++
}
}
return n
}
func safeGetUsername(c *gin.Context) (string, error) {
username, exists := c.Get("username")
if !exists {
@@ -356,7 +380,7 @@ func UpdateOwnCommandAddress(c *gin.Context) {
return
}
rateLimitKey := fmt.Sprintf("update_own_addr:%s", clientUsername)
rateLimitKey := ownAddressRateLimitKey(clientUsername)
if !checkRateLimit(rateLimitKey) {
c.JSON(http.StatusTooManyRequests, gin.H{"error": "Trop de requêtes, réessayez plus tard"})
return
@@ -746,6 +770,39 @@ func GetAvailableDeliveryPersons(c *gin.Context) {
return
}
// Enrichissement en un seul aller-retour groupé (statut, position, queue,
// compteurs) au lieu de laisser le frontend refaire un appel par livreur.
usernames := make([]string, len(livreurs))
for i, l := range livreurs {
if u, ok := l["username"].(string); ok {
usernames[i] = u
}
}
detailsByUsername := database.GetDeliveryPersonsDetailsBatch(usernames)
for i, l := range livreurs {
username, _ := l["username"].(string)
det := detailsByUsername[username]
if det == nil {
det = &db.DeliveryPersonDetails{Status: "offline"}
}
l["status"] = det.Status
l["queue_size"] = det.QueueSize
l["total_deliveries"] = det.TotalDeliveries
l["completed_deliveries"] = det.CompletedDeliveries
l["pending_deliveries"] = det.PendingDeliveries
if det.CurrentCommand != 0 {
l["current_command"] = det.CurrentCommand
} else {
l["current_command"] = nil
}
if det.HasLocation {
l["location"] = gin.H{"latitude": det.Latitude, "longitude": det.Longitude}
} else {
l["location"] = nil
}
livreurs[i] = l
}
log.Printf("✅ [GET_LIVREURS] Trouvés: %d livreurs disponibles", len(livreurs))
c.JSON(http.StatusOK, gin.H{