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:
56
backend/internal/middleware/auth.go
Normal file
56
backend/internal/middleware/auth.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
userIDKey contextKey = "user_id"
|
||||
userPlanKey contextKey = "user_plan"
|
||||
)
|
||||
|
||||
// TokenClaims represents the result of validating an access token.
|
||||
type TokenClaims struct {
|
||||
UserID string
|
||||
Plan string
|
||||
}
|
||||
|
||||
// AccessTokenValidator validates JWT access tokens.
|
||||
type AccessTokenValidator interface {
|
||||
ValidateAccessToken(tokenStr string) (*TokenClaims, error)
|
||||
}
|
||||
|
||||
func Auth(validator AccessTokenValidator) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := strings.TrimPrefix(header, "Bearer ")
|
||||
claims, err := validator.ValidateAccessToken(tokenStr)
|
||||
if err != nil {
|
||||
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userIDKey, claims.UserID)
|
||||
ctx = context.WithValue(ctx, userPlanKey, claims.Plan)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func UserIDFromCtx(ctx context.Context) string {
|
||||
id, _ := ctx.Value(userIDKey).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
func UserPlanFromCtx(ctx context.Context) string {
|
||||
plan, _ := ctx.Value(userPlanKey).(string)
|
||||
return plan
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
18
backend/internal/middleware/cors.go
Normal file
18
backend/internal/middleware/cors.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/cors"
|
||||
)
|
||||
|
||||
func CORS(allowedOrigins []string) func(http.Handler) http.Handler {
|
||||
return cors.Handler(cors.Options{
|
||||
AllowedOrigins: allowedOrigins,
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Authorization", "Content-Type", "X-Request-ID"},
|
||||
ExposedHeaders: []string{"X-Request-ID"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: 300,
|
||||
})
|
||||
}
|
||||
34
backend/internal/middleware/logging.go
Normal file
34
backend/internal/middleware/logging.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (rw *responseWriter) WriteHeader(code int) {
|
||||
rw.statusCode = code
|
||||
rw.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ww := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
|
||||
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
slog.Info("request",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", ww.statusCode,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"request_id", RequestIDFromCtx(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
23
backend/internal/middleware/recovery.go
Normal file
23
backend/internal/middleware/recovery.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
slog.Error("panic recovered",
|
||||
"error", err,
|
||||
"stack", string(debug.Stack()),
|
||||
"request_id", RequestIDFromCtx(r.Context()),
|
||||
)
|
||||
http.Error(w, `{"error":"internal server error"}`, http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
49
backend/internal/middleware/recovery_test.go
Normal file
49
backend/internal/middleware/recovery_test.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRecovery_NoPanic(t *testing.T) {
|
||||
handler := Recovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("expected 200, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecovery_CatchesPanic(t *testing.T) {
|
||||
handler := Recovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
panic("test panic")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecovery_CatchesPanicWithError(t *testing.T) {
|
||||
handler := Recovery(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
panic(42)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Errorf("expected 500, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
29
backend/internal/middleware/request_id.go
Normal file
29
backend/internal/middleware/request_id.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const requestIDKey contextKey = "request_id"
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-ID")
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), requestIDKey, id)
|
||||
w.Header().Set("X-Request-ID", id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func RequestIDFromCtx(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey).(string)
|
||||
return id
|
||||
}
|
||||
59
backend/internal/middleware/request_id_test.go
Normal file
59
backend/internal/middleware/request_id_test.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRequestID_GeneratesNew(t *testing.T) {
|
||||
handler := RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := RequestIDFromCtx(r.Context())
|
||||
if id == "" {
|
||||
t.Error("expected non-empty request ID in context")
|
||||
}
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Header().Get("X-Request-ID") == "" {
|
||||
t.Error("expected X-Request-ID in response header")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestID_PreservesExisting(t *testing.T) {
|
||||
handler := RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := RequestIDFromCtx(r.Context())
|
||||
if id != "existing-id" {
|
||||
t.Errorf("expected 'existing-id', got %q", id)
|
||||
}
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
req.Header.Set("X-Request-ID", "existing-id")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(rr, req)
|
||||
if rr.Header().Get("X-Request-ID") != "existing-id" {
|
||||
t.Error("expected preserved X-Request-ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestID_UniquePerRequest(t *testing.T) {
|
||||
var ids []string
|
||||
handler := RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ids = append(ids, RequestIDFromCtx(r.Context()))
|
||||
}))
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
}
|
||||
|
||||
if ids[0] == ids[1] || ids[1] == ids[2] {
|
||||
t.Error("expected unique IDs for each request")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user