Skip to content

Commit c8dfc2a

Browse files
committed
refactor(auth): improve authentication logging
- Added detailed logging - Improved error handling
1 parent c977fa4 commit c8dfc2a

File tree

3 files changed

+48
-22
lines changed

3 files changed

+48
-22
lines changed

lib/src/middlewares/authentication_middleware.dart

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,43 +23,53 @@ Middleware authenticationProvider() {
2323
AuthTokenService tokenService;
2424
try {
2525
print(
26-
'[AuthMiddleware] Attempting to read AuthTokenService...'); // Log 2: Before read
26+
'[AuthMiddleware] Attempting to read AuthTokenService...',
27+
); // Log 2: Before read
2728
tokenService = context.read<AuthTokenService>();
2829
print(
29-
'[AuthMiddleware] Successfully read AuthTokenService.'); // Log 3: After read
30+
'[AuthMiddleware] Successfully read AuthTokenService.',
31+
); // Log 3: After read
3032
} catch (e, s) {
3133
print(
32-
'[AuthMiddleware] FAILED to read AuthTokenService: $e\n$s'); // Log Error
34+
'[AuthMiddleware] FAILED to read AuthTokenService: $e\n$s',
35+
); // Log Error
3336
// Re-throw the error to be caught by the main error handler
3437
rethrow;
3538
}
3639
User? user; // Initialize user as null
3740

3841
// Extract the Authorization header
3942
print(
40-
'[AuthMiddleware] Attempting to read Authorization header...'); // Log 4: Before header read
43+
'[AuthMiddleware] Attempting to read Authorization header...',
44+
); // Log 4: Before header read
4145
final authHeader = context.request.headers['Authorization'];
4246
print(
43-
'[AuthMiddleware] Authorization header value: $authHeader'); // Log 5: Header value
47+
'[AuthMiddleware] Authorization header value: $authHeader',
48+
); // Log 5: Header value
4449

4550
if (authHeader != null && authHeader.startsWith('Bearer ')) {
4651
// Extract the token string
4752
final token = authHeader.substring(7); // Length of 'Bearer '
4853
print(
49-
'[AuthMiddleware] Extracted Bearer token.'); // Log 6: Token extracted
54+
'[AuthMiddleware] Extracted Bearer token.',
55+
); // Log 6: Token extracted
5056
try {
5157
print(
52-
'[AuthMiddleware] Attempting to validate token...'); // Log 7: Before validate
58+
'[AuthMiddleware] Attempting to validate token...',
59+
); // Log 7: Before validate
5360
// Validate the token using the service
5461
user = await tokenService.validateToken(token);
5562
print(
56-
'[AuthMiddleware] Token validation returned: ${user?.id ?? 'null'}'); // Log 8: After validate
63+
'[AuthMiddleware] Token validation returned: ${user?.id ?? 'null'}',
64+
); // Log 8: After validate
5765
if (user != null) {
5866
print(
59-
'[AuthMiddleware] Authentication successful for user: ${user.id}');
67+
'[AuthMiddleware] Authentication successful for user: ${user.id}',
68+
);
6069
} else {
6170
print(
62-
'[AuthMiddleware] Invalid token provided (validateToken returned null).');
71+
'[AuthMiddleware] Invalid token provided (validateToken returned null).',
72+
);
6373
// Optional: Could throw UnauthorizedException here if *all* routes
6474
// using this middleware strictly require a valid token.
6575
// However, providing null allows routes to handle optional auth.
@@ -73,7 +83,8 @@ Middleware authenticationProvider() {
7383
} catch (e, s) {
7484
// Catch unexpected errors during validation
7585
print(
76-
'[AuthMiddleware] Unexpected error during token validation: $e\n$s');
86+
'[AuthMiddleware] Unexpected error during token validation: $e\n$s',
87+
);
7788
user = null; // Keep user null if unexpected error occurred
7889
}
7990
} else {
@@ -83,7 +94,8 @@ Middleware authenticationProvider() {
8394
// Provide the User object (or null) into the context
8495
// This makes `context.read<User?>()` available downstream.
8596
print(
86-
'[AuthMiddleware] Providing User (${user?.id ?? 'null'}) to context.'); // Log 9: Before provide
97+
'[AuthMiddleware] Providing User (${user?.id ?? 'null'}) to context.',
98+
); // Log 9: Before provide
8799
return handler(context.provide<User?>(() => user));
88100
};
89101
};

lib/src/services/simple_auth_token_service.dart

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,15 @@ class SimpleAuthTokenService implements AuthTokenService {
4646

4747
try {
4848
print(
49-
'[SimpleAuthTokenService] Attempting to read user from repository...');
49+
'[SimpleAuthTokenService] Attempting to read user from repository...',
50+
);
5051
final user = await _userRepository.read(userId);
5152
print('[SimpleAuthTokenService] User read successful: ${user.id}');
5253
return user;
5354
} on NotFoundException {
5455
print(
55-
'[SimpleAuthTokenService] Validation failed: User ID $userId not found.');
56+
'[SimpleAuthTokenService] Validation failed: User ID $userId not found.',
57+
);
5658
// Return null if user not found, mimicking successful validation
5759
// of a token for a non-existent user. The middleware handles this.
5860
return null;

routes/_middleware.dart

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -250,11 +250,17 @@ Handler middleware(Handler handler) {
250250
.use(provider<HtDataRepository<Category>>((_) => categoryRepository))
251251
.use(provider<HtDataRepository<Source>>((_) => sourceRepository))
252252
.use(provider<HtDataRepository<Country>>((_) => countryRepository))
253-
.use(provider<HtDataRepository<User>>(
254-
(_) => userRepository)) // Used by Auth services
253+
.use(
254+
provider<HtDataRepository<User>>(
255+
(_) => userRepository,
256+
),
257+
) // Used by Auth services
255258
.use(provider<HtAppSettingsRepository>((_) => settingsRepository))
256-
.use(provider<HtEmailRepository>(
257-
(_) => emailRepository)) // Used by AuthService
259+
.use(
260+
provider<HtEmailRepository>(
261+
(_) => emailRepository,
262+
),
263+
) // Used by AuthService
258264

259265
// --- 4. Authentication Service Providers (Auth Logic Dependencies) ---
260266
// PURPOSE: Provide the core services needed for authentication logic.
@@ -264,15 +270,21 @@ Handler middleware(Handler handler) {
264270
// - `AuthService` uses several repositories and `AuthTokenService`.
265271
// - `VerificationCodeStorageService` is used by `AuthService`.
266272
// - `Uuid` is used by `AuthService` and `JwtAuthTokenService`.
267-
.use(provider<AuthTokenService>(
268-
(_) => authTokenService)) // Read by authenticationProvider
273+
.use(
274+
provider<AuthTokenService>(
275+
(_) => authTokenService,
276+
),
277+
) // Read by authenticationProvider
269278
.use(
270279
provider<VerificationCodeStorageService>(
271280
(_) => verificationCodeStorageService,
272281
),
273282
) // Read by AuthService
274-
.use(provider<AuthService>(
275-
(_) => authService)) // Reads other services/repos
283+
.use(
284+
provider<AuthService>(
285+
(_) => authService,
286+
),
287+
) // Reads other services/repos
276288
.use(provider<Uuid>((_) => uuid)) // Read by AuthService & TokenService
277289

278290
// --- 5. Authentication Middleware (User Context Population) ---

0 commit comments

Comments
 (0)