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,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');
}
}