58 lines
1.7 KiB
Go
58 lines
1.7 KiB
Go
|
|
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)
|
||
|
|
}
|
||
|
|
}
|