Files
shared/backend/auth/account_routes_test.go
T

65 lines
2.4 KiB
Go

package auth
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-chi/chi/v5"
)
func TestProfileReportsTheSessionUser(t *testing.T) {
guard := newRoleAuthGuard(t)
auth := NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
router := chi.NewRouter()
auth.MountAccountRoutes(router)
anonymous := httptest.NewRecorder()
router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil))
if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` {
t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String())
}
request := httptest.NewRequest(http.MethodGet, "/profile", nil)
request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"})
known := httptest.NewRecorder()
router.ServeHTTP(known, request)
var body struct{ User map[string]any }
if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" {
t.Fatalf("profile = %s, %v", known.Body.String(), err)
}
}
type loginRequiredStore struct{}
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
// loginOffStore is loginRequiredStore with login switched off for the whole application.
type loginOffStore struct{ loginRequiredStore }
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
func newRoleAuthGuard(t *testing.T) *httptest.Server {
t.Helper()
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
if !ok || r.URL.Path != "/api/me" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
}))
t.Cleanup(server.Close)
return server
}