diff --git a/easyauth.go b/easyauth.go index 1a77eaf..dd78af9 100644 --- a/easyauth.go +++ b/easyauth.go @@ -2,6 +2,7 @@ package auth import ( "context" + "errors" "fmt" "net/http" "time" @@ -42,6 +43,21 @@ func (e EasyAuth) CheckUser(w http.ResponseWriter, r *http.Request) (AuthentikUs return user, nil } +func (e EasyAuth) Middelware(next http.HandlerFunc) http.HandlerFunc { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, err := e.CheckUser(w, r) + if err != nil { + if !errors.Is(err, ErrUserNeedRedirect) { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(fmt.Sprintf("panic doing auth: %v", err.Error()))) + } + return + } + ctx := context.WithValue(r.Context(), "user", user) + next.ServeHTTP(w, r.WithContext(ctx)) // call ServeHTTP on the original handler + }) +} + func (e EasyAuth) GetUser(w http.ResponseWriter, r *http.Request) (AuthentikUser, bool, error) { store, err := session.Start(context.Background(), w, r) if err != nil {