@@ -195,7 +195,9 @@ Handler middleware(Handler handler) {
195
195
print ('[MiddlewareSetup] JwtAuthTokenService instantiated.' ); // Updated log
196
196
final verificationCodeStorageService =
197
197
InMemoryVerificationCodeStorageService ();
198
- print ('[MiddlewareSetup] InMemoryVerificationCodeStorageService instantiated.' ); // Added log
198
+ print (
199
+ '[MiddlewareSetup] InMemoryVerificationCodeStorageService instantiated.' ,
200
+ ); // Added log
199
201
final authService = AuthService (
200
202
userRepository: userRepository,
201
203
authTokenService: authTokenService,
@@ -205,11 +207,23 @@ Handler middleware(Handler handler) {
205
207
);
206
208
print ('[MiddlewareSetup] AuthService instantiated.' ); // Added log
207
209
208
- // Chain the providers and other middleware
210
+ // ==========================================================================
211
+ // MIDDLEWARE CHAIN
212
+ // ==========================================================================
213
+ // IMPORTANT: The order of middleware matters significantly!
214
+ // Middleware is applied in layers (like an onion). A request flows "in"
215
+ // through the chain, hits the route handler, and the response flows "out".
216
+ // Providers must be added *before* the middleware/handlers that read them.
217
+ // Error handlers should typically be placed late in the "request" phase
218
+ // (or early in the "response" phase) to catch errors from upstream.
219
+ // ==========================================================================
209
220
return handler
210
- // --- Request ID Provider ---
211
- // Generate a unique ID for each request and provide it via context.
212
- // Using the RequestId wrapper ensures type safety for context reads.
221
+ // --- 1. Request ID Provider (Early Setup) ---
222
+ // PURPOSE: Generates a unique ID (UUID v4) for each incoming request.
223
+ // Provides `RequestId` instance via context.
224
+ // ORDER: Placed *very early* so the ID is available for logging and
225
+ // tracing throughout the entire request lifecycle in all
226
+ // subsequent middleware and handlers.
213
227
.use ((innerHandler) {
214
228
return (context) {
215
229
final requestIdValue = uuid.v4 ();
@@ -218,35 +232,74 @@ Handler middleware(Handler handler) {
218
232
return innerHandler (context.provide <RequestId >(() => requestId));
219
233
};
220
234
})
221
- // Provide the Model Registry Map
222
- .use (
223
- modelRegistryProvider,
224
- ) // Uses the provider defined in model_registry.dart
225
235
226
- // Provide each specific repository instance
236
+ // --- 2. Model Registry Provider (Early Setup) ---
237
+ // PURPOSE: Provides the `ModelRegistry` map for dynamic JSON
238
+ // serialization/deserialization lookups.
239
+ // ORDER: Needed by some repository clients or handlers dealing with
240
+ // generic data types. Placed early, after RequestId.
241
+ .use (modelRegistryProvider)
242
+
243
+ // --- 3. Repository Providers (Core Data Access) ---
244
+ // PURPOSE: Provide singleton instances of all data repositories.
245
+ // ORDER: These MUST be provided BEFORE any middleware or route handlers
246
+ // that need to interact with data (e.g., AuthService,
247
+ // authenticationProvider indirectly via AuthService/TokenService,
248
+ // specific route logic).
227
249
.use (provider <HtDataRepository <Headline >>((_) => headlineRepository))
228
250
.use (provider <HtDataRepository <Category >>((_) => categoryRepository))
229
251
.use (provider <HtDataRepository <Source >>((_) => sourceRepository))
230
252
.use (provider <HtDataRepository <Country >>((_) => countryRepository))
253
+ .use (provider <HtDataRepository <User >>(
254
+ (_) => userRepository)) // Used by Auth services
231
255
.use (provider <HtAppSettingsRepository >((_) => settingsRepository))
232
- // --- Provide Auth Dependencies ---
233
- .use (provider <HtDataRepository <User >>((_) => userRepository))
234
- .use (provider <HtEmailRepository >((_) => emailRepository))
235
- // Provide the AuthTokenService interface type
236
- .use (provider <AuthTokenService >((_) => authTokenService))
256
+ .use (provider <HtEmailRepository >(
257
+ (_) => emailRepository)) // Used by AuthService
258
+
259
+ // --- 4. Authentication Service Providers (Auth Logic Dependencies) ---
260
+ // PURPOSE: Provide the core services needed for authentication logic.
261
+ // ORDER: These MUST be provided BEFORE `authenticationProvider` and
262
+ // any route handlers that perform authentication/authorization.
263
+ // - `AuthTokenService` is read directly by `authenticationProvider`.
264
+ // - `AuthService` uses several repositories and `AuthTokenService`.
265
+ // - `VerificationCodeStorageService` is used by `AuthService`.
266
+ // - `Uuid` is used by `AuthService` and `JwtAuthTokenService`.
267
+ .use (provider <AuthTokenService >(
268
+ (_) => authTokenService)) // Read by authenticationProvider
237
269
.use (
238
270
provider <VerificationCodeStorageService >(
239
271
(_) => verificationCodeStorageService,
240
272
),
241
- )
242
- .use (provider <AuthService >((_) => authService))
243
- // --- Provide UUID ---
244
- .use (provider <Uuid >((_) => uuid)) // Provide Uuid instance
273
+ ) // Read by AuthService
274
+ .use (provider <AuthService >(
275
+ (_) => authService)) // Reads other services/repos
276
+ .use (provider <Uuid >((_) => uuid)) // Read by AuthService & TokenService
245
277
246
- // --- Core Middleware ---
247
- // Apply authenticationProvider first (after providers)
278
+ // --- 5. Authentication Middleware (User Context Population) ---
279
+ // PURPOSE: Reads the `Authorization: Bearer <token>` header, validates
280
+ // the token using `AuthTokenService`, and provides the
281
+ // resulting `User?` object into the context.
282
+ // ORDER: MUST come AFTER `AuthTokenService` is provided (which it reads).
283
+ // Should come BEFORE any route handlers that need to know the
284
+ // currently authenticated user (`context.read<User?>()`).
248
285
.use (authenticationProvider ())
249
- .use (requestLogger ()) // Then basic request logging
250
- // Error handler should generally be last to catch all upstream errors
286
+
287
+ // --- 6. Request Logger (Logging) ---
288
+ // PURPOSE: Logs details about the incoming request and outgoing response.
289
+ // ORDER: Often placed late in the request phase / early in the response
290
+ // phase. Placing it here logs the request *before* the handler
291
+ // runs and the response *after* the handler (and error handler)
292
+ // completes. Can access `RequestId` and potentially `User?`.
293
+ .use (requestLogger ())
294
+
295
+ // --- 7. Error Handler (Catch-All) ---
296
+ // PURPOSE: Catches exceptions thrown by upstream middleware or route
297
+ // handlers and converts them into standardized JSON error responses.
298
+ // ORDER: MUST be placed *late* in the chain (typically last before the
299
+ // actual handler is invoked by the framework, or first in the
300
+ // response processing flow) so it can catch errors from
301
+ // everything that came before it (providers, auth middleware,
302
+ // route handlers). If placed too early, it won't catch errors
303
+ // from middleware/handlers defined after it.
251
304
.use (errorHandler ());
252
305
}
0 commit comments