61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
|
|
package handler
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"net/http"
|
||
|
|
"net/http/httptest"
|
||
|
|
"testing"
|
||
|
|
|
||
|
|
"img_infinite_canvas/internal/domain/design"
|
||
|
|
)
|
||
|
|
|
||
|
|
type fakeBearerAuthenticator struct{}
|
||
|
|
|
||
|
|
func (fakeBearerAuthenticator) UserIDFromBearer(_ context.Context, authorization string) (string, bool) {
|
||
|
|
if authorization == "Bearer valid" {
|
||
|
|
return "91cd197b-8255-4172-9981-77391fd38f33", true
|
||
|
|
}
|
||
|
|
return "", false
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestUserContextMiddlewareUsesAuthorizationHeader(t *testing.T) {
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/api/projects", nil)
|
||
|
|
req.Header.Set("Authorization", "Bearer valid")
|
||
|
|
rec := httptest.NewRecorder()
|
||
|
|
|
||
|
|
called := false
|
||
|
|
UserContextMiddleware(fakeBearerAuthenticator{})(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
called = true
|
||
|
|
if got := design.UserIDFromContext(r.Context()); got != "91cd197b-8255-4172-9981-77391fd38f33" {
|
||
|
|
t.Fatalf("expected authenticated user in context, got %s", got)
|
||
|
|
}
|
||
|
|
w.WriteHeader(http.StatusNoContent)
|
||
|
|
})(rec, req)
|
||
|
|
|
||
|
|
if !called {
|
||
|
|
t.Fatal("expected next handler to be called")
|
||
|
|
}
|
||
|
|
if rec.Code != http.StatusNoContent {
|
||
|
|
t.Fatalf("expected status %d, got %d", http.StatusNoContent, rec.Code)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestUserContextMiddlewareIgnoresLegacyTokenHeaderAndCookie(t *testing.T) {
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/api/projects", nil)
|
||
|
|
req.Header.Set("token", "valid")
|
||
|
|
req.AddCookie(&http.Cookie{Name: "usertoken", Value: "valid"})
|
||
|
|
rec := httptest.NewRecorder()
|
||
|
|
|
||
|
|
called := false
|
||
|
|
UserContextMiddleware(fakeBearerAuthenticator{})(func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
called = true
|
||
|
|
})(rec, req)
|
||
|
|
|
||
|
|
if called {
|
||
|
|
t.Fatal("expected next handler not to be called")
|
||
|
|
}
|
||
|
|
if rec.Code != http.StatusUnauthorized {
|
||
|
|
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, rec.Code)
|
||
|
|
}
|
||
|
|
}
|