46 lines
1.3 KiB
Go
46 lines
1.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"math/big"
|
|
"path/filepath"
|
|
"strings"
|
|
"unicode"
|
|
|
|
"golang.org/x/text/runes"
|
|
"golang.org/x/text/transform"
|
|
"golang.org/x/text/unicode/norm"
|
|
)
|
|
|
|
func GenerateUniqueFileName(productName string, originalFileName string) string {
|
|
n, _ := rand.Int(rand.Reader, big.NewInt(1000000))
|
|
randomString := fmt.Sprintf("%d", n.Int64())
|
|
ext := filepath.Ext(originalFileName)
|
|
return fmt.Sprintf("%s_%s%s", productName, randomString, ext)
|
|
}
|
|
|
|
// SanitizeFilePath valide qu'un chemin de fichier local reste bien dans le
|
|
// dossier uploads/ et ne contient pas de tentative de path traversal.
|
|
func SanitizeFilePath(path string) (string, error) {
|
|
cleaned := filepath.Clean(path)
|
|
|
|
if strings.Contains(cleaned, "..") {
|
|
return "", fmt.Errorf("path traversal détecté")
|
|
}
|
|
|
|
if !strings.HasPrefix(cleaned, "uploads/") && !strings.HasPrefix(cleaned, "uploads\\") {
|
|
return "", fmt.Errorf("chemin invalide")
|
|
}
|
|
|
|
return cleaned, nil
|
|
}
|
|
|
|
// NormalizeAddress supprime les accents et normalise les espaces, pour
|
|
// comparer deux adresses saisies différemment (casse/accents/espaces).
|
|
func NormalizeAddress(s string) string {
|
|
t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
|
|
result, _, _ := transform.String(t, s)
|
|
return strings.Join(strings.Fields(result), " ")
|
|
}
|