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" "io"
"log" "log"
"net/http" "net/http"
"strings"
"time" "time"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
) )
var MySigningKey = []byte("COUCOU")
type LoginInformation struct { type LoginInformation struct {
Email string `json:"email"` Email string `json:"email"`
Password string `json:"password"` Password string `json:"password"`
@@ -70,3 +73,47 @@ func HandleLogin(w http.ResponseWriter, r *http.Request) {
fmt.Println(signed) 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)
})
}

View File

@@ -77,13 +77,16 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
http.HandleFunc("/", handler) mux := http.NewServeMux()
http.HandleFunc("/user/new", handlerCreateUser) HandleRoutes(mux, map[string]Handler{
http.HandleFunc("/users/login", HandleLogin) "/": {handler, nil},
"/users/login": {HandleLogin, nil},
"/users/new": {handlerCreateUser, AuthJWT},
})
fmt.Printf("Serving on port %s\n", port) 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 { if err != nil {
fmt.Printf("Error starting server: %s\n", err) fmt.Printf("Error starting server: %s\n", err)
} }

25
backend/router.go Normal file
View File

@@ -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,
)
}
}
}