Files
dumpsterChat/internal/middleware/session.go
T
hobokenchicken bda4c9d73d fix: handle 401 gracefully on web; add Bearer token auth for Tauri
- fetchMe() no longer surfaces 401 as a user-facing error (it just
  means 'no session', not a failure)
- API client auto-clears auth state on 401 mid-session so the user
  gets redirected to login instead of seeing 'ERR: Request failed: 401'
- Session middleware now accepts Authorization: Bearer <token> header
  as fallback when no cookie is present (for Tauri/native clients)
- Login, register, and WebAuthn endpoints expose X-Session-Token header
  so non-browser clients can capture the token
2026-07-16 14:46:17 -04:00

63 lines
1.4 KiB
Go

package middleware
import (
"context"
"net/http"
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/config"
)
type contextKey string
const UserContextKey contextKey = "user_id"
type SessionStore interface {
GetUserIDByToken(ctx context.Context, token string) (string, error)
}
func Session(store SessionStore, cfg *config.Config) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
cookie, err := r.Cookie(cfg.Session.CookieName)
if err == nil {
token = cookie.Value
} else {
authHeader := r.Header.Get("Authorization")
if len(authHeader) > 7 && authHeader[:7] == "Bearer " {
token = authHeader[7:]
}
}
if token == "" {
next.ServeHTTP(w, r)
return
}
userID, err := store.GetUserIDByToken(r.Context(), token)
if err != nil {
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), UserContextKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func UserIDFromContext(ctx context.Context) (string, bool) {
id, ok := ctx.Value(UserContextKey).(string)
return id, ok
}
func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, ok := UserIDFromContext(r.Context()); !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}