feat: implement Iteration 0 foundation (backend + Flutter client)
Backend (Go): - Project structure with chi router, pgxpool, goose migrations - JWT auth (access/refresh tokens) with Firebase token verification - NoopTokenVerifier for local dev without Firebase credentials - PostgreSQL user repository with atomic profile updates (transactions) - Mifflin-St Jeor calorie calculation based on profile data - REST API: POST /auth/login, /auth/refresh, /auth/logout, GET/PUT /profile, GET /health - Middleware: auth, CORS (localhost wildcard), logging, recovery, request_id - Unit tests (51 passing) and integration tests (testcontainers) - Docker Compose setup with postgres healthcheck and graceful shutdown Flutter client: - Riverpod state management with GoRouter navigation - Firebase Auth (email/password + Google sign-in with web popup support) - Platform-aware API URLs (web/Android/iOS) - Dio HTTP client with JWT auth interceptor and concurrent refresh handling - Secure token storage - Screens: Login, Register, Home (tabs: Menu, Recipes, Products, Profile) - Unit tests (17 passing) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
192
backend/internal/middleware/auth_test.go
Normal file
192
backend/internal/middleware/auth_test.go
Normal file
@@ -0,0 +1,192 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// testJWTClaims mirrors auth.Claims for test token generation without importing auth.
|
||||
type testJWTClaims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Plan string `json:"plan"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func generateTestToken(secret string, userID, plan string, duration time.Duration) string {
|
||||
claims := testJWTClaims{
|
||||
UserID: userID,
|
||||
Plan: plan,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
s, _ := token.SignedString([]byte(secret))
|
||||
return s
|
||||
}
|
||||
|
||||
// testValidator implements AccessTokenValidator for tests.
|
||||
type testAccessValidator struct {
|
||||
secret string
|
||||
}
|
||||
|
||||
func (v *testAccessValidator) ValidateAccessToken(tokenStr string) (*TokenClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenStr, &testJWTClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
return []byte(v.secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
claims, ok := token.Claims.(*testJWTClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
return &TokenClaims{UserID: claims.UserID, Plan: claims.Plan}, nil
|
||||
}
|
||||
|
||||
// failingValidator always returns an error.
|
||||
type failingValidator struct{}
|
||||
|
||||
func (v *failingValidator) ValidateAccessToken(tokenStr string) (*TokenClaims, error) {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
func TestAuth_ValidToken(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
token := generateTestToken("test-secret", "user-1", "free", 15*time.Minute)
|
||||
|
||||
handler := Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
userID := UserIDFromCtx(r.Context())
|
||||
if userID != "user-1" {
|
||||
t.Errorf("expected user-1, got %s", userID)
|
||||
}
|
||||
plan := UserPlanFromCtx(r.Context())
|
||||
if plan != "free" {
|
||||
t.Errorf("expected free, got %s", plan)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_MissingHeader(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
|
||||
handler := Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_InvalidBearerFormat(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
|
||||
handler := Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Basic abc123")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_ExpiredToken(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
token := generateTestToken("test-secret", "user-1", "free", -1*time.Second)
|
||||
|
||||
handler := Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_InvalidToken(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
|
||||
handler := Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer invalid-token")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_PaidPlan(t *testing.T) {
|
||||
validator := &testAccessValidator{secret: "test-secret"}
|
||||
token := generateTestToken("test-secret", "user-1", "paid", 15*time.Minute)
|
||||
|
||||
handler := Auth(validator)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
plan := UserPlanFromCtx(r.Context())
|
||||
if plan != "paid" {
|
||||
t.Errorf("expected paid, got %s", plan)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuth_EmptyBearer(t *testing.T) {
|
||||
handler := Auth(&failingValidator{})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Error("handler should not be called")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("Authorization", "Bearer ")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user