Proper routing sir
This commit is contained in:
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user