chore(Easyauth): add middelware

This commit is contained in:
kekskurse 2024-11-21 19:26:13 +01:00
parent a14596c55a
commit eb7b9dcf40

View file

@ -2,6 +2,7 @@ package auth
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/http" "net/http"
"time" "time"
@ -42,6 +43,21 @@ func (e EasyAuth) CheckUser(w http.ResponseWriter, r *http.Request) (AuthentikUs
return user, nil 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) { func (e EasyAuth) GetUser(w http.ResponseWriter, r *http.Request) (AuthentikUser, bool, error) {
store, err := session.Start(context.Background(), w, r) store, err := session.Start(context.Background(), w, r)
if err != nil { if err != nil {