feat: add proper redirects

This commit is contained in:
Lukas Werner 2025-08-31 10:20:03 -07:00
parent 7b7bebe701
commit a617298b5d
No known key found for this signature in database

View File

@ -7,6 +7,8 @@ import (
"encoding/json" "encoding/json"
"html/template" "html/template"
"net/http" "net/http"
"net/http/cookiejar"
"net/url"
"sync" "sync"
"time" "time"
@ -95,6 +97,25 @@ func generateRandomToken() string {
return base64.StdEncoding.EncodeToString(b) return base64.StdEncoding.EncodeToString(b)
} }
func setRedirectCookie(w http.ResponseWriter, path string) {
http.SetCookie(w,
&http.Cookie{
Name: "redirect_on_completion",
Value: path,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}
func getRedirectFromCookie(r *http.Request) string {
cookie, err := r.Cookie("redirect_on_completion")
if err != nil {
return "/"
}
return cookie.Value
}
//go:embed templates/LoginPage.html //go:embed templates/LoginPage.html
var loginPageContent string var loginPageContent string
@ -152,7 +173,6 @@ func (s *OAuthStore) LoginPage() http.Handler {
func (s *OAuthStore) Protected(next http.Handler) http.Handler { func (s *OAuthStore) Protected(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(SessionCookie) cookie, err := r.Cookie(SessionCookie)
if err != nil { if err != nil {
sendToLoginPage(w, r) sendToLoginPage(w, r)
@ -160,6 +180,7 @@ func (s *OAuthStore) Protected(next http.Handler) http.Handler {
} }
sess, exists := s.GetSession(cookie.Value) sess, exists := s.GetSession(cookie.Value)
if !exists { if !exists {
setRedirectCookie(w, r.URL.Path)
sendToLoginPage(w, r) sendToLoginPage(w, r)
return return
} }
@ -213,15 +234,22 @@ func (s *OAuthStore) CallbackHandler() http.Handler {
Path: "/", Path: "/",
}) })
// clear cookie redirect := getRedirectFromCookie(r)
// clear cookies
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
Name: "oauth_state", Name: "oauth_state",
Value: "", Value: "",
MaxAge: -1, MaxAge: -1,
}) })
http.SetCookie(w, &http.Cookie{
Name: "redirect_on_completion",
Value: "",
MaxAge: -1,
})
// TODO: remember what path the user was on and redirect them back there after doing the whole login process // TODO: remember what path the user was on and redirect them back there after doing the whole login process
http.Redirect(w, r, "/", http.StatusTemporaryRedirect) http.Redirect(w, r, redirect, http.StatusTemporaryRedirect)
}) })
} }