Proper routing sir

This commit is contained in:
cdricms
2025-01-15 13:31:57 +01:00
parent 683a8c3133
commit 3ac25f2a83
3 changed files with 79 additions and 4 deletions

View File

@@ -7,11 +7,14 @@ import (
"io"
"log"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
var MySigningKey = []byte("COUCOU")
type LoginInformation struct {
Email string `json:"email"`
Password string `json:"password"`
@@ -70,3 +73,47 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
fmt.Println(signed)
}
func HandleMiddlewareRoute(pattern string,
handler func(w http.ResponseWriter, r *http.Request),
middleware func(http.Handler) http.Handler,
mux *http.ServeMux,
) {
mux.HandleFunc(pattern, handler)
http.Handle(pattern, middleware(mux))
}
func AuthJWT(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the Authorization header is provided
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Missing Authorization header", http.StatusUnauthorized)
return
}
// Bearer token is expected, so split the header into "Bearer <token>"
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
http.Error(w, "Invalid Authorization header format", http.StatusUnauthorized)
return
}
// Parse the token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Ensure that the token's signing method is valid
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return MySigningKey, nil
})
if err != nil || !token.Valid {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// Call the next handler if the JWT is valid
next.ServeHTTP(w, r)
})
}