34 lines
692 B
Go
34 lines
692 B
Go
package midlleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"git.ostiwe.com/ostiwe-com/status/repository"
|
|
"github.com/go-chi/jwtauth/v5"
|
|
)
|
|
|
|
func SetUserFromJWT(next http.Handler) http.Handler {
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := r.Context()
|
|
token, _, err := jwtauth.FromContext(ctx)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
}
|
|
|
|
userRepo := repository.NewUserRepository()
|
|
user, err := userRepo.FindByLogin(token.Subject())
|
|
if err != nil || user == nil {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
return
|
|
}
|
|
|
|
ctx = context.WithValue(ctx, "user", user)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
}
|
|
return http.HandlerFunc(fn)
|
|
}
|