api: add user-resolution middleware and POST /api/setup
resolveUser attaches the session's provisioned geniusrun user (if any) to request context without blocking; requireProvisionedUser (wired fully in Task 13) 403s routes that need one. GET /api/session/me now reports has_profile/display_name so the frontend can show the setup screen.
This commit is contained in:
57
backend/internal/api/usercontext_test.go
Normal file
57
backend/internal/api/usercontext_test.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"geniusrun/backend/internal/auth"
|
||||
)
|
||||
|
||||
func TestResolveUser_AttachesResolvedUserWhenProvisioned(t *testing.T) {
|
||||
s, db := newTestServer(t)
|
||||
userID, err := db.ProvisionUser(context.Background(), "test-user", "Test User")
|
||||
if err != nil {
|
||||
t.Fatalf("ProvisionUser: %v", err)
|
||||
}
|
||||
|
||||
var gotUserID int64
|
||||
var gotOK bool
|
||||
handler := auth.RequireSession(testSessionConfig.Secret)(s.resolveUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
u, ok := userFromContext(r.Context())
|
||||
gotUserID, gotOK = u.ID, ok
|
||||
})))
|
||||
|
||||
rec := doJSON(t, handler, http.MethodGet, "/", nil) // doJSON's test cookie carries Sub: "test-user"
|
||||
_ = rec
|
||||
if !gotOK || gotUserID != userID {
|
||||
t.Fatalf("resolveUser: ok=%v userID=%d, want ok=true userID=%d", gotOK, gotUserID, userID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveUser_LeavesContextEmptyWhenNotProvisioned(t *testing.T) {
|
||||
s, _ := newTestServer(t)
|
||||
|
||||
var gotOK bool
|
||||
handler := auth.RequireSession(testSessionConfig.Secret)(s.resolveUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, gotOK = userFromContext(r.Context())
|
||||
})))
|
||||
|
||||
doJSON(t, handler, http.MethodGet, "/", nil) // "test-user" sub, never provisioned in this test
|
||||
if gotOK {
|
||||
t.Fatal("expected userFromContext to report not-found for an unprovisioned sub")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireProvisionedUser_RejectsWhenNoUserResolved(t *testing.T) {
|
||||
handler := requireProvisionedUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("handler should not be reached")
|
||||
}))
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403", rec.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user