start setting up auth handler

This commit is contained in:
juancwu 2025-12-15 21:50:54 -05:00
commit 979a415b95
4 changed files with 62 additions and 0 deletions

16
internal/ctxkeys/ctx.go Normal file
View file

@ -0,0 +1,16 @@
package ctxkeys
import (
"context"
"git.juancwu.dev/juancwu/budgething/internal/model"
)
const (
UserKey string = "user"
)
func User(ctx context.Context) *model.User {
user, _ := ctx.Value(UserKey).(*model.User)
return user
}

15
internal/handler/auth.go Normal file
View file

@ -0,0 +1,15 @@
package handler
import "net/http"
type authHandler struct {
}
func NewAuthHandler() *authHandler {
return &authHandler{}
}
func (h *authHandler) AuthPage(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("200 OK"))
}

View file

@ -0,0 +1,24 @@
package middleware
import (
"net/http"
"git.juancwu.dev/juancwu/budgething/internal/ctxkeys"
)
// RequireGuest ensures request is not authenticated
func RequireGuest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user := ctxkeys.User(r.Context())
if user != nil {
if r.Header.Get("HX-Request") == "true" {
w.Header().Set("HX-Redirect", "/app/dashboard")
w.WriteHeader(http.StatusSeeOther)
return
}
http.Redirect(w, r, "/app/dashboard", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
}
}

View file

@ -6,14 +6,21 @@ import (
"git.juancwu.dev/juancwu/budgething/assets"
"git.juancwu.dev/juancwu/budgething/internal/app"
"git.juancwu.dev/juancwu/budgething/internal/handler"
"git.juancwu.dev/juancwu/budgething/internal/middleware"
)
func SetupRoutes(a *app.App) http.Handler {
auth := handler.NewAuthHandler()
mux := http.NewServeMux()
// Static
sub, _ := fs.Sub(assets.AssetsFS, ".")
mux.Handle("GET /assets/", http.StripPrefix("/assets/", http.FileServer(http.FS(sub))))
// Auth pages
mux.HandleFunc("GET /auth", middleware.RequireGuest(auth.AuthPage))
return mux
}