feat: Added basic user authorization
This commit is contained in:
33
router/midlleware/user.go
Normal file
33
router/midlleware/user.go
Normal file
@@ -0,0 +1,33 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user