diff options
| author | soler_j <soler_j@etna-alternance.net> | 2025-05-04 21:41:04 +0200 |
|---|---|---|
| committer | soler_j <soler_j@etna-alternance.net> | 2025-05-04 21:41:04 +0200 |
| commit | 40f7e50b91374ce17b6dce514cf371e5629192eb (patch) | |
| tree | 0bd69cc56e97fd8e4e9b52b24381a01924e4d850 /app/internal/utils/middleware.go | |
| parent | dc3c72813a6358cde4c1bb3d1eaf618c6d46c460 (diff) | |
Ajout de la gestion des middlewares pour le logging et l'authentification, ainsi que la fonction de chaƮnage des middlewares.
Diffstat (limited to 'app/internal/utils/middleware.go')
| -rw-r--r-- | app/internal/utils/middleware.go | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/app/internal/utils/middleware.go b/app/internal/utils/middleware.go new file mode 100644 index 0000000..5133916 --- /dev/null +++ b/app/internal/utils/middleware.go @@ -0,0 +1,66 @@ +package utils + +import ( + "log" + "net/http" + "os" + "time" + + "github.com/golang-jwt/jwt/v5" +) + +func LogMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + next.ServeHTTP(w, r) + duration := time.Since(start) + + log.Printf("Request: %s %s took %f seconds", r.Method, r.URL.Path, duration.Seconds()) + }) +} + +/** + * AuthMiddleware is a placeholder for authentication middleware. + * In a real application, this would check for valid authentication tokens or sessions. + * For now, it just calls the next handler. + */ +func AuthMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authHeader := r.Header.Get("Authorization") + if authHeader == "" { + RespondWithError(w, http.StatusUnauthorized, "Missing authorization header") + return + } + tokenString := authHeader[len("Bearer "):] + token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + // Validate the algorithm + if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { + return nil, http.ErrNotSupported + } + // Return the secret key for validation + return []byte(os.Getenv("JWT_SECRET")), nil + }) + if err != nil { + RespondWithError(w, http.StatusUnauthorized, "Invalid token") + return + } + if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { + // You can access claims here + log.Printf("User ID: %v", claims["user_id"]) + } else { + RespondWithError(w, http.StatusUnauthorized, "Invalid token claims") + return + } + + next.ServeHTTP(w, r) + }) +} + +func Chain(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + for _, middleware := range middlewares { + next = middleware(next) + } + return next + } +} |
