chore(easyAuth): redirect to last get request page

This commit is contained in:
kekskurse 2024-09-26 11:45:47 +02:00
parent 969a4505ed
commit 66a2845764

View file

@ -27,23 +27,20 @@ func NewEasyAuth(client Auth) (EasyAuth, error) {
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) {
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
SetCookie(w, "url", r.URL.String(), time.Now().Add(1*time.Minute)) setCookie(w, "url", r.URL.String(), time.Now().Add(1*time.Minute))
} }
cookie, err := r.Cookie("jwt")
cookieValue, err := getCookie(w, r, "jwt")
if err != nil { if err != nil {
if errors.Is(err, http.ErrNoCookie) {
e.redirectAuth(w, r)
return AuthentikUser{}, false, nil
}
return AuthentikUser{}, false, err return AuthentikUser{}, false, err
} }
if cookie.Value == "" { if cookieValue == "" {
e.redirectAuth(w, r) e.redirectAuth(w, r)
return AuthentikUser{}, false, nil return AuthentikUser{}, false, nil
} }
parsedAccessToken, _ := jwt.ParseWithClaims(cookie.Value, &UserClaims{}, func(token *jwt.Token) (interface{}, error) { parsedAccessToken, _ := jwt.ParseWithClaims(cookieValue, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
return e.jwtSecret, nil return e.jwtSecret, nil
}) })
@ -90,15 +87,33 @@ func (e EasyAuth) AuthHTTPHandler(w http.ResponseWriter, r *http.Request) {
panic(err) // TODO: Deal with error panic(err) // TODO: Deal with error
} }
SetCookie(w, "jwt", jwtString, expired) setCookie(w, "jwt", jwtString, expired)
_, err = w.Write([]byte("ok")) // TODO: Redirect to right page redirectURL, err := getCookie(w, r, "url")
if err != nil { if err != nil {
panic(err) // TODO: Deal with error panic(err) // TODO: Deal with error
} }
if redirectURL == "" {
redirectURL = "/"
}
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
} }
func SetCookie(w http.ResponseWriter, name, value string, expired time.Time) { func getCookie(w http.ResponseWriter, r *http.Request, name string) (string, error) {
cookie, err := r.Cookie(name)
if err != nil {
if errors.Is(err, http.ErrNoCookie) {
return "", nil
}
return "", err
}
return cookie.Value, nil
}
func setCookie(w http.ResponseWriter, name, value string, expired time.Time) {
cookie := http.Cookie{} cookie := http.Cookie{}
cookie.Name = name cookie.Name = name
cookie.Value = value cookie.Value = value