From 3ac25f2a830e570f1b6a8ff8bf8080dd6418d844 Mon Sep 17 00:00:00 2001 From: cdricms <36056008+cdricms@users.noreply.github.com> Date: Wed, 15 Jan 2025 13:31:57 +0100 Subject: [PATCH] Proper routing sir --- backend/auth.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ backend/main.go | 11 +++++++---- backend/router.go | 25 +++++++++++++++++++++++++ 3 files changed, 79 insertions(+), 4 deletions(-) create mode 100644 backend/router.go diff --git a/backend/auth.go b/backend/auth.go index 2e3645e..9c55e6b 100644 --- a/backend/auth.go +++ b/backend/auth.go @@ -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 " + 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) + }) +} diff --git a/backend/main.go b/backend/main.go index 68e6260..fbd9c7d 100644 --- a/backend/main.go +++ b/backend/main.go @@ -77,13 +77,16 @@ func main() { log.Fatal(err) } - http.HandleFunc("/", handler) + mux := http.NewServeMux() - http.HandleFunc("/user/new", handlerCreateUser) - http.HandleFunc("/users/login", HandleLogin) + HandleRoutes(mux, map[string]Handler{ + "/": {handler, nil}, + "/users/login": {HandleLogin, nil}, + "/users/new": {handlerCreateUser, AuthJWT}, + }) fmt.Printf("Serving on port %s\n", port) - err = http.ListenAndServe(fmt.Sprintf(":%s", port), nil) + err = http.ListenAndServe(fmt.Sprintf(":%s", port), mux) if err != nil { fmt.Printf("Error starting server: %s\n", err) } diff --git a/backend/router.go b/backend/router.go new file mode 100644 index 0000000..aaf2133 --- /dev/null +++ b/backend/router.go @@ -0,0 +1,25 @@ +package main + +import "net/http" + +type HandlerFunc func(w http.ResponseWriter, r *http.Request) + +type Handler struct { + Handler HandlerFunc + Middleware func(http.Handler) http.Handler +} + +func HandleRoutes(mux *http.ServeMux, routes map[string]Handler) { + for pattern, handler := range routes { + if handler.Middleware == nil { + mux.HandleFunc(pattern, handler.Handler) + } else { + HandleMiddlewareRoute( + pattern, + handler.Handler, + handler.Middleware, + mux, + ) + } + } +}