go-jwtserver/middleware/jwt.go

38 lines
1.1 KiB
Go

package middleware
import (
"context"
"log"
"net/http"
)
// JwtAuthentication is a Jwt Auth controller with postgres database
var JwtAuthentication = func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
notAuth := []string{"/api/user/new", "/api/user/login", "/api/user/refresh"} //List of endpoints that doesn't require auth
requestPath := r.URL.Path //current request path
//check if request does not need authentication, serve the request if it doesn't need it
for _, value := range notAuth {
if value == requestPath {
next.ServeHTTP(w, r)
return
}
}
tk, err := ValidateToken(w, r)
if err != nil {
return
}
//Everything went well, proceed with the request and set the caller to the user retrieved from the parsed token
log.Printf("User %v", tk) //Useful for monitoring
ctx := context.WithValue(r.Context(), "user", tk.UserID)
r = r.WithContext(ctx)
next.ServeHTTP(w, r) //proceed in the middleware chain!
})
}