go-jwtserver/middleware/jwt.go

38 lines
1.1 KiB
Go
Raw Normal View History

2020-07-16 13:56:57 +02:00
package middleware
2020-07-16 10:51:50 +02:00
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) {
2020-07-21 11:08:01 +02:00
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
2020-07-16 10:51:50 +02:00
//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
}
}
2020-07-21 11:08:01 +02:00
tk, err := ValidateToken(w, r)
if err != nil {
2020-07-16 10:51:50 +02:00
return
}
//Everything went well, proceed with the request and set the caller to the user retrieved from the parsed token
2020-07-21 11:08:01 +02:00
log.Printf("User %v", tk) //Useful for monitoring
ctx := context.WithValue(r.Context(), "user", tk.UserID)
2020-07-16 10:51:50 +02:00
r = r.WithContext(ctx)
next.ServeHTTP(w, r) //proceed in the middleware chain!
})
}