From eb7b9dcf404e5b82e39892a631eb7d35ccfd9de4 Mon Sep 17 00:00:00 2001 From: kekskurse Date: Thu, 21 Nov 2024 19:26:13 +0100 Subject: [PATCH] chore(Easyauth): add middelware --- easyauth.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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 {