Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Harden auth impl #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
fulleni merged 22 commits into main from harden_auth_impl
Jul 20, 2025
Merged
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
cedbe20
chore(env): add JWT secret key requirement and update CORS origin
fulleni Jul 20, 2025
f0b2068
feat(config): add JWT secret key environment variable retrieval
fulleni Jul 20, 2025
1639d16
refactor(auth): replace hardcoded secret key with environment variable
fulleni Jul 20, 2025
a1468cb
feat(auth): add MongoDB token blacklist service
fulleni Jul 20, 2025
0d5e933
refactor(config): replace token blacklist service
fulleni Jul 20, 2025
01a2e5e
feat(auth): Add MongoDB verification code storage
fulleni Jul 20, 2025
0cb5741
refactor(mongodb): Improve verification code storage
fulleni Jul 20, 2025
8e74597
refactor(services): Replace in-memory verification code storage
fulleni Jul 20, 2025
1550783
refactor(services): remove unnecessary initialization
fulleni Jul 20, 2025
eb04f61
refactor(services): remove unnecessary init method
fulleni Jul 20, 2025
8e52d81
feat(database): add indexes to verification codes and tokens
fulleni Jul 20, 2025
48cbcfe
refactor(auth): replace print statements with logging
fulleni Jul 20, 2025
76589a3
fix(authorization): replace print statements with logger
fulleni Jul 20, 2025
7349220
fix(error_handler): use logger instead of print
fulleni Jul 20, 2025
2ea1f83
refactor: remove unused auth & verification services
fulleni Jul 20, 2025
74935bf
fix(auth): improve anonymous auth error handling
fulleni Jul 20, 2025
981e366
fix(auth): improve error handling in delete-account
fulleni Jul 20, 2025
205acd8
fix(auth): improve error handling in request-code handler
fulleni Jul 20, 2025
ee01c85
fix(auth): improve sign-out error logging
fulleni Jul 20, 2025
170539f
fix: improve error logging in verify-code handler
fulleni Jul 20, 2025
85a289b
fix(api): replace print statements with logger
fulleni Jul 20, 2025
89e2417
feat(auth): configure JWT issuer and expiry
fulleni Jul 20, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(auth): replace print statements with logging
- Replaced `print` statements with `Logger`.
- Improved logging for better debugging.
- Added error handling for token validation.
- Used finer logging for detailed info.
- Improved logging messages clarity.
  • Loading branch information
fulleni committed Jul 20, 2025
commit 48cbcfe311411daa090a8c523fa35acf88bf5ddd
49 changes: 26 additions & 23 deletions lib/src/middlewares/authentication_middleware.dart
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import 'package:dart_frog/dart_frog.dart';
import 'package:ht_api/src/services/auth_token_service.dart';
import 'package:ht_shared/ht_shared.dart';
import 'package:logging/logging.dart';

final _log = Logger('AuthMiddleware');

/// Middleware to handle authentication by verifying Bearer tokens.
///
Expand All @@ -17,69 +20,69 @@ import 'package:ht_shared/ht_shared.dart';
Middleware authenticationProvider() {
return (handler) {
return (context) async {
print('[AuthMiddleware] Entered.');
_log.finer('Entered.');
// Read the interface type
AuthTokenService tokenService;
try {
print('[AuthMiddleware] Attempting to read AuthTokenService...');
_log.finer('Attempting to read AuthTokenService...');
tokenService = context.read<AuthTokenService>();
print('[AuthMiddleware] Successfully read AuthTokenService.');
_log.finer('Successfully read AuthTokenService.');
} catch (e, s) {
print('[AuthMiddleware] FAILED to read AuthTokenService: $e\n$s');
_log.severe('FAILED to read AuthTokenService.', e, s);
// Re-throw the error to be caught by the main error handler
rethrow;
}
User? user;

// Extract the Authorization header
print('[AuthMiddleware] Attempting to read Authorization header...');
_log.finer('Attempting to read Authorization header...');
final authHeader = context.request.headers['Authorization'];
print('[AuthMiddleware] Authorization header value: $authHeader');
_log.finer('Authorization header value: $authHeader');

if (authHeader != null && authHeader.startsWith('Bearer ')) {
// Extract the token string
final token = authHeader.substring(7); // Length of 'Bearer '
print('[AuthMiddleware] Extracted Bearer token.');
_log.finer('Extracted Bearer token.');
try {
print('[AuthMiddleware] Attempting to validate token...');
_log.finer('Attempting to validate token...');
// Validate the token using the service
user = await tokenService.validateToken(token);
print(
'[AuthMiddleware] Token validation returned: ${user?.id ?? 'null'}',
_log.finer(
'Token validation returned: ${user?.id ?? 'null'}',
);
if (user != null) {
print(
'[AuthMiddleware] Authentication successful for user: ${user.id}',
);
_log.info('Authentication successful for user: ${user.id}');
} else {
print(
'[AuthMiddleware] Invalid token provided (validateToken returned null).',
_log.warning(
'Invalid token provided (validateToken returned null).',
);
// Optional: Could throw UnauthorizedException here if *all* routes
// using this middleware strictly require a valid token.
// However, providing null allows routes to handle optional auth.
}
} on HtHttpException catch (e) {
// Log token validation errors from the service
print('Token validation failed: $e');
_log.warning('Token validation failed.', e);
// Let the error propagate if needed, or handle specific cases.
// For now, we treat validation errors as resulting in no user.
user = null; // Keep user null if HtHttpException occurred
} catch (e, s) {
// Catch unexpected errors during validation
print(
'[AuthMiddleware] Unexpected error during token validation: $e\n$s',
_log.severe(
'Unexpected error during token validation.',
e,
s,
);
user = null; // Keep user null if unexpected error occurred
}
} else {
print('[AuthMiddleware] No valid Bearer token found in header.');
_log.finer('No valid Bearer token found in header.');
}

// Provide the User object (or null) into the context
// This makes `context.read<User?>()` available downstream.
print(
'[AuthMiddleware] Providing User (${user?.id ?? 'null'}) to context.',
_log.finer(
'Providing User (${user?.id ?? 'null'}) to context.',
);
return handler(context.provide<User?>(() => user));
};
Expand All @@ -96,14 +99,14 @@ Middleware requireAuthentication() {
return (context) {
final user = context.read<User?>();
if (user == null) {
print(
_log.warning(
'Authentication required but no valid user found. Denying access.',
);
// Throwing allows the central errorHandler to create the 401 response.
throw const UnauthorizedException('Authentication required.');
}
// If user exists, proceed to the handler
print('Authentication check passed for user: ${user.id}');
_log.info('Authentication check passed for user: ${user.id}');
return handler(context.provide<User>(() => user));
};
};
Expand Down

AltStyle γ«γ‚ˆγ£γ¦ε€‰ζ›γ•γ‚ŒγŸγƒšγƒΌγ‚Έ (->γ‚ͺγƒͺγ‚ΈγƒŠγƒ«) /