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:
dbastrikin
2026-02-20 13:14:58 +02:00
commit 24219b611e
140 changed files with 13062 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
import 'package:dio/dio.dart';
import '../auth/secure_storage.dart';
import 'auth_interceptor.dart';
class ApiClient {
late final Dio _dio;
ApiClient({required String baseUrl, required SecureStorageService storage}) {
_dio = Dio(BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 30),
headers: {'Content-Type': 'application/json'},
));
_dio.interceptors.addAll([
AuthInterceptor(storage: storage, dio: _dio),
LogInterceptor(requestBody: true, responseBody: true),
]);
}
/// Exposed for testing only.
ApiClient.withDio(this._dio);
Future<Map<String, dynamic>> get(String path,
{Map<String, dynamic>? params}) async {
final response = await _dio.get(path, queryParameters: params);
return response.data;
}
Future<Map<String, dynamic>> post(String path, {dynamic data}) async {
final response = await _dio.post(path, data: data);
return response.data;
}
Future<Map<String, dynamic>> put(String path, {dynamic data}) async {
final response = await _dio.put(path, data: data);
return response.data;
}
Future<Map<String, dynamic>> delete(String path) async {
final response = await _dio.delete(path);
return response.data;
}
}

View File

@@ -0,0 +1,22 @@
class ApiException implements Exception {
final String message;
final int? statusCode;
const ApiException(this.message, {this.statusCode});
@override
String toString() => 'ApiException($statusCode): $message';
}
class UnauthorizedException extends ApiException {
const UnauthorizedException([super.message = 'Unauthorized'])
: super(statusCode: 401);
}
class BadRequestException extends ApiException {
const BadRequestException(super.message) : super(statusCode: 400);
}
class NetworkException extends ApiException {
const NetworkException([super.message = 'No internet connection']);
}

View File

@@ -0,0 +1,94 @@
import 'package:dio/dio.dart';
import '../auth/secure_storage.dart';
class AuthInterceptor extends Interceptor {
final SecureStorageService _storage;
final Dio _dio;
// Prevents multiple simultaneous token refresh requests
bool _isRefreshing = false;
final List<({RequestOptions options, ErrorInterceptorHandler handler})>
_pendingRequests = [];
AuthInterceptor({required SecureStorageService storage, required Dio dio})
: _storage = storage,
_dio = dio;
@override
Future<void> onRequest(
RequestOptions options,
RequestInterceptorHandler handler,
) async {
if (options.path.startsWith('/auth/')) {
return handler.next(options);
}
final token = await _storage.getAccessToken();
if (token != null) {
options.headers['Authorization'] = 'Bearer $token';
}
handler.next(options);
}
@override
Future<void> onError(
DioException err,
ErrorInterceptorHandler handler,
) async {
if (err.response?.statusCode != 401) {
return handler.next(err);
}
final refreshToken = await _storage.getRefreshToken();
if (refreshToken == null) {
return handler.next(err);
}
// If a refresh is already in progress, queue this request
if (_isRefreshing) {
_pendingRequests.add((options: err.requestOptions, handler: handler));
return;
}
_isRefreshing = true;
try {
final response = await _dio.post('/auth/refresh', data: {
'refresh_token': refreshToken,
});
final newAccessToken = response.data['access_token'] as String;
final newRefreshToken = response.data['refresh_token'] as String;
await _storage.saveTokens(
accessToken: newAccessToken,
refreshToken: newRefreshToken,
);
// Retry the original request
final retryOptions = err.requestOptions;
retryOptions.headers['Authorization'] = 'Bearer $newAccessToken';
final retryResponse = await _dio.fetch(retryOptions);
handler.resolve(retryResponse);
// Retry all pending requests with the new token
for (final pending in _pendingRequests) {
pending.options.headers['Authorization'] = 'Bearer $newAccessToken';
try {
final r = await _dio.fetch(pending.options);
pending.handler.resolve(r);
} catch (e) {
pending.handler.next(err);
}
}
} catch (_) {
await _storage.clearTokens();
handler.next(err);
for (final pending in _pendingRequests) {
pending.handler.next(err);
}
} finally {
_isRefreshing = false;
_pendingRequests.clear();
}
}
}

View File

@@ -0,0 +1,160 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../shared/models/user.dart';
import '../api/api_client.dart';
import '../config/app_config.dart';
import 'auth_service.dart';
import 'secure_storage.dart';
import 'package:firebase_auth/firebase_auth.dart' as fb;
enum AuthStatus { unknown, authenticated, unauthenticated }
class AuthState {
final AuthStatus status;
final User? user;
final bool isLoading;
final String? error;
const AuthState({
this.status = AuthStatus.unknown,
this.user,
this.isLoading = false,
this.error,
});
AuthState copyWith({
AuthStatus? status,
User? user,
bool? isLoading,
String? error,
}) {
return AuthState(
status: status ?? this.status,
user: user ?? this.user,
isLoading: isLoading ?? this.isLoading,
error: error,
);
}
}
class AuthNotifier extends StateNotifier<AuthState> {
final AuthService? _authService;
AuthNotifier(AuthService authService) : _authService = authService, super(const AuthState()) {
_checkAuth();
}
@visibleForTesting
AuthNotifier.test(super.initialState)
: _authService = null;
Future<void> _checkAuth() async {
final isAuth = await _authService!.isAuthenticated();
state = state.copyWith(
status: isAuth ? AuthStatus.authenticated : AuthStatus.unauthenticated,
);
}
Future<void> signInWithEmail(String email, String password) async {
state = state.copyWith(isLoading: true, error: null);
try {
final user = await _authService!.signInWithEmail(email, password);
state = AuthState(
status: AuthStatus.authenticated,
user: user,
);
} catch (e) {
state = state.copyWith(
isLoading: false,
error: _mapError(e),
);
}
}
Future<void> signInWithGoogle() async {
state = state.copyWith(isLoading: true, error: null);
try {
final user = await _authService!.signInWithGoogle();
state = AuthState(
status: AuthStatus.authenticated,
user: user,
);
} catch (e) {
state = state.copyWith(
isLoading: false,
error: _mapError(e),
);
}
}
Future<void> register(String email, String password, String name) async {
state = state.copyWith(isLoading: true, error: null);
try {
final user =
await _authService!.registerWithEmail(email, password, name);
state = AuthState(
status: AuthStatus.authenticated,
user: user,
);
} catch (e) {
state = state.copyWith(
isLoading: false,
error: _mapError(e),
);
}
}
Future<void> signOut() async {
await _authService!.signOut();
state = const AuthState(status: AuthStatus.unauthenticated);
}
String _mapError(dynamic e) {
if (e is fb.FirebaseAuthException) {
switch (e.code) {
case 'wrong-password':
case 'user-not-found':
return 'Неверный email или пароль';
case 'email-already-in-use':
return 'Email уже зарегистрирован';
case 'weak-password':
return 'Пароль слишком простой';
case 'invalid-email':
return 'Некорректный email';
default:
return 'Ошибка авторизации: ${e.message}';
}
}
return 'Произошла ошибка. Попробуйте позже.';
}
}
final appConfigProvider = Provider<AppConfig>((ref) {
return AppConfig.development;
});
final secureStorageProvider = Provider<SecureStorageService>((ref) {
return SecureStorageService();
});
final apiClientProvider = Provider<ApiClient>((ref) {
final config = ref.read(appConfigProvider);
final storage = ref.read(secureStorageProvider);
return ApiClient(
baseUrl: config.apiBaseUrl,
storage: storage,
);
});
final authServiceProvider = Provider<AuthService>((ref) {
return AuthService(
firebaseAuth: fb.FirebaseAuth.instance,
apiClient: ref.read(apiClientProvider),
storage: ref.read(secureStorageProvider),
);
});
final authProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
return AuthNotifier(ref.read(authServiceProvider));
});

View File

@@ -0,0 +1,92 @@
import 'package:firebase_auth/firebase_auth.dart' as fb;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:google_sign_in/google_sign_in.dart';
import '../../shared/models/user.dart';
import '../api/api_client.dart';
import 'secure_storage.dart';
class AuthService {
final fb.FirebaseAuth _firebaseAuth;
final ApiClient _apiClient;
final SecureStorageService _storage;
AuthService({
required fb.FirebaseAuth firebaseAuth,
required ApiClient apiClient,
required SecureStorageService storage,
}) : _firebaseAuth = firebaseAuth,
_apiClient = apiClient,
_storage = storage;
Future<User> signInWithGoogle() async {
if (kIsWeb) {
// На вебе используем signInWithPopup — открывает Google popup в браузере
final provider = fb.GoogleAuthProvider();
final userCredential = await _firebaseAuth.signInWithPopup(provider);
return _authenticateWithBackend(userCredential);
} else {
// На мобильных используем google_sign_in
final googleUser = await GoogleSignIn().signIn();
if (googleUser == null) {
throw Exception('Google sign-in cancelled');
}
final googleAuth = await googleUser.authentication;
final credential = fb.GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
final userCredential =
await _firebaseAuth.signInWithCredential(credential);
return _authenticateWithBackend(userCredential);
}
}
Future<User> signInWithEmail(String email, String password) async {
final userCredential = await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
return _authenticateWithBackend(userCredential);
}
Future<User> registerWithEmail(
String email, String password, String name) async {
final userCredential = await _firebaseAuth.createUserWithEmailAndPassword(
email: email,
password: password,
);
await userCredential.user!.updateDisplayName(name);
return _authenticateWithBackend(userCredential);
}
Future<User> _authenticateWithBackend(fb.UserCredential credential) async {
final idToken = await credential.user!.getIdToken();
final response = await _apiClient.post('/auth/login', data: {
'firebase_token': idToken,
});
await _storage.saveTokens(
accessToken: response['access_token'],
refreshToken: response['refresh_token'],
);
return User.fromJson(response['user']);
}
Future<void> signOut() async {
try {
await _apiClient.post('/auth/logout');
} catch (_) {
// Don't block logout on backend failure
}
await _firebaseAuth.signOut();
await _storage.clearTokens();
}
Future<bool> isAuthenticated() async {
final token = await _storage.getAccessToken();
return token != null;
}
}

View File

@@ -0,0 +1,24 @@
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureStorageService {
final FlutterSecureStorage _storage;
SecureStorageService({FlutterSecureStorage? storage})
: _storage = storage ?? const FlutterSecureStorage();
Future<void> saveTokens({
required String accessToken,
required String refreshToken,
}) async {
await _storage.write(key: 'access_token', value: accessToken);
await _storage.write(key: 'refresh_token', value: refreshToken);
}
Future<String?> getAccessToken() => _storage.read(key: 'access_token');
Future<String?> getRefreshToken() => _storage.read(key: 'refresh_token');
Future<void> clearTokens() async {
await _storage.delete(key: 'access_token');
await _storage.delete(key: 'refresh_token');
}
}

View File

@@ -0,0 +1,25 @@
import 'package:flutter/foundation.dart' show kIsWeb, defaultTargetPlatform, TargetPlatform;
class AppConfig {
final String apiBaseUrl;
const AppConfig({required this.apiBaseUrl});
static AppConfig get development {
if (kIsWeb) {
return const AppConfig(apiBaseUrl: 'http://localhost:9090');
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return const AppConfig(apiBaseUrl: 'http://10.0.2.2:9090');
case TargetPlatform.iOS:
return const AppConfig(apiBaseUrl: 'http://localhost:9090');
default:
return const AppConfig(apiBaseUrl: 'http://localhost:9090');
}
}
static const production = AppConfig(
apiBaseUrl: 'https://api.food-ai.app',
);
}

View File

@@ -0,0 +1,93 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../auth/auth_provider.dart';
import '../../features/auth/login_screen.dart';
import '../../features/auth/register_screen.dart';
import '../../features/home/home_screen.dart';
import '../../features/products/products_screen.dart';
import '../../features/menu/menu_screen.dart';
import '../../features/recipes/recipes_screen.dart';
import '../../features/profile/profile_screen.dart';
final routerProvider = Provider<GoRouter>((ref) {
final authState = ref.watch(authProvider);
return GoRouter(
initialLocation: '/home',
redirect: (context, state) {
final isLoggedIn = authState.status == AuthStatus.authenticated;
final isAuthRoute = state.matchedLocation.startsWith('/auth');
if (authState.status == AuthStatus.unknown) return null;
if (!isLoggedIn && !isAuthRoute) return '/auth/login';
if (isLoggedIn && isAuthRoute) return '/home';
return null;
},
routes: [
GoRoute(
path: '/auth/login',
builder: (_, __) => const LoginScreen(),
),
GoRoute(
path: '/auth/register',
builder: (_, __) => const RegisterScreen(),
),
ShellRoute(
builder: (context, state, child) => MainShell(child: child),
routes: [
GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),
GoRoute(
path: '/products',
builder: (_, __) => const ProductsScreen()),
GoRoute(path: '/menu', builder: (_, __) => const MenuScreen()),
GoRoute(
path: '/recipes', builder: (_, __) => const RecipesScreen()),
GoRoute(
path: '/profile', builder: (_, __) => const ProfileScreen()),
],
),
],
);
});
class MainShell extends StatelessWidget {
final Widget child;
const MainShell({super.key, required this.child});
static const _tabs = [
'/home',
'/products',
'/menu',
'/recipes',
'/profile',
];
@override
Widget build(BuildContext context) {
final location = GoRouterState.of(context).matchedLocation;
final currentIndex = _tabs.indexOf(location).clamp(0, _tabs.length - 1);
return Scaffold(
body: child,
bottomNavigationBar: BottomNavigationBar(
currentIndex: currentIndex,
onTap: (index) => context.go(_tabs[index]),
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home), label: 'Главная'),
BottomNavigationBarItem(
icon: Icon(Icons.kitchen), label: 'Продукты'),
BottomNavigationBarItem(
icon: Icon(Icons.calendar_month), label: 'Меню'),
BottomNavigationBarItem(
icon: Icon(Icons.menu_book), label: 'Рецепты'),
BottomNavigationBarItem(
icon: Icon(Icons.person), label: 'Профиль'),
],
),
);
}
}

View File

@@ -0,0 +1,29 @@
import 'package:flutter/material.dart';
abstract class AppColors {
// Primary
static const primary = Color(0xFF4CAF50);
static const primaryLight = Color(0xFF81C784);
static const primaryDark = Color(0xFF388E3C);
// Accent
static const accent = Color(0xFFFF9800);
// Background
static const background = Color(0xFFF5F5F5);
static const surface = Color(0xFFFFFFFF);
// Text
static const textPrimary = Color(0xFF212121);
static const textSecondary = Color(0xFF757575);
// Status
static const error = Color(0xFFE53935);
static const warning = Color(0xFFFFA726);
static const success = Color(0xFF66BB6A);
// Shelf life indicators
static const freshGreen = Color(0xFF4CAF50);
static const warningYellow = Color(0xFFFFC107);
static const expiredRed = Color(0xFFE53935);
}

View File

@@ -0,0 +1,31 @@
import 'package:flutter/material.dart';
import 'app_colors.dart';
ThemeData appTheme() {
return ThemeData(
useMaterial3: true,
colorSchemeSeed: AppColors.primary,
scaffoldBackgroundColor: AppColors.background,
appBarTheme: const AppBarTheme(
centerTitle: true,
elevation: 0,
backgroundColor: AppColors.surface,
foregroundColor: AppColors.textPrimary,
),
bottomNavigationBarTheme: const BottomNavigationBarThemeData(
selectedItemColor: AppColors.primary,
unselectedItemColor: AppColors.textSecondary,
type: BottomNavigationBarType.fixed,
),
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
),
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
minimumSize: const Size(double.infinity, 48),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
);
}