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:
45
client/lib/core/api/api_client.dart
Normal file
45
client/lib/core/api/api_client.dart
Normal 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;
|
||||
}
|
||||
}
|
||||
22
client/lib/core/api/api_exceptions.dart
Normal file
22
client/lib/core/api/api_exceptions.dart
Normal 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']);
|
||||
}
|
||||
94
client/lib/core/api/auth_interceptor.dart
Normal file
94
client/lib/core/api/auth_interceptor.dart
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user