Skip to content

Commit 92be6b3

Browse files
committed
feat(auth): add simple auth token service
- Implemented simple token service - For debugging purposes - Uses in-memory user repo
1 parent cc89be2 commit 92be6b3

File tree

3 files changed

+83
-9
lines changed

3 files changed

+83
-9
lines changed

lib/src/services/jwt_auth_token_service.dart

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,8 @@ class JwtAuthTokenService implements AuthTokenService {
100100
String? userId;
101101
if (subClaim is String) {
102102
userId = subClaim;
103-
print('[validateToken] "sub" claim successfully cast to String: $userId');
103+
print(
104+
'[validateToken] "sub" claim successfully cast to String: $userId');
104105
} else if (subClaim != null) {
105106
print(
106107
'[validateToken] WARNING: "sub" claim is not a String. '
@@ -115,7 +116,8 @@ class JwtAuthTokenService implements AuthTokenService {
115116
}
116117

117118
if (userId == null || userId.isEmpty) {
118-
print('[validateToken] Token validation failed: Missing or empty "sub" claim.');
119+
print(
120+
'[validateToken] Token validation failed: Missing or empty "sub" claim.');
119121
// Throw specific exception for malformed token
120122
throw const BadRequestException(
121123
'Malformed token: Missing or empty subject claim.',
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import 'package:ht_api/src/services/auth_token_service.dart';
2+
import 'package:ht_data_repository/ht_data_repository.dart';
3+
import 'package:ht_shared/ht_shared.dart';
4+
5+
/// {@template simple_auth_token_service}
6+
/// A minimal, dependency-free implementation of [AuthTokenService] for debugging.
7+
///
8+
/// Generates simple, predictable tokens and validates them by checking a prefix
9+
/// and fetching the user from the repository. Does not involve JWT logic.
10+
/// {@endtemplate}
11+
class SimpleAuthTokenService implements AuthTokenService {
12+
/// {@macro simple_auth_token_service}
13+
const SimpleAuthTokenService({
14+
required HtDataRepository<User> userRepository,
15+
}) : _userRepository = userRepository;
16+
17+
final HtDataRepository<User> _userRepository;
18+
static const String _tokenPrefix = 'valid-token-for-user-id:';
19+
20+
@override
21+
Future<String> generateToken(User user) async {
22+
print('[SimpleAuthTokenService] Generating token for user ${user.id}');
23+
final token = '$_tokenPrefix${user.id}';
24+
print('[SimpleAuthTokenService] Generated token: $token');
25+
// Simulate async operation if needed, though not strictly necessary here
26+
await Future<void>.delayed(Duration.zero);
27+
return token;
28+
}
29+
30+
@override
31+
Future<User?> validateToken(String token) async {
32+
print('[SimpleAuthTokenService] Attempting to validate token: $token');
33+
if (!token.startsWith(_tokenPrefix)) {
34+
print('[SimpleAuthTokenService] Validation failed: Invalid prefix.');
35+
// Mimic JWT behavior by throwing Unauthorized for invalid format
36+
throw const UnauthorizedException('Invalid token format.');
37+
}
38+
39+
final userId = token.substring(_tokenPrefix.length);
40+
print('[SimpleAuthTokenService] Extracted user ID: $userId');
41+
42+
if (userId.isEmpty) {
43+
print('[SimpleAuthTokenService] Validation failed: Empty user ID.');
44+
throw const UnauthorizedException('Invalid token: Empty user ID.');
45+
}
46+
47+
try {
48+
print('[SimpleAuthTokenService] Attempting to read user from repository...');
49+
final user = await _userRepository.read(userId);
50+
print('[SimpleAuthTokenService] User read successful: ${user.id}');
51+
return user;
52+
} on NotFoundException {
53+
print('[SimpleAuthTokenService] Validation failed: User ID $userId not found.');
54+
// Return null if user not found, mimicking successful validation
55+
// of a token for a non-existent user. The middleware handles this.
56+
return null;
57+
} on HtHttpException catch (e, s) {
58+
// Handle other potential repository errors
59+
print(
60+
'[SimpleAuthTokenService] Validation failed: Repository error $e\n$s',
61+
);
62+
// Re-throw other client/repo exceptions
63+
rethrow;
64+
} catch (e, s) {
65+
// Catch unexpected errors during validation
66+
print('[SimpleAuthTokenService] Unexpected validation error: $e\n$s');
67+
throw OperationFailedException(
68+
'Simple token validation failed unexpectedly: $e',
69+
);
70+
}
71+
}
72+
}

routes/_middleware.dart

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ import 'package:ht_api/src/middlewares/error_handler.dart';
1111
import 'package:ht_api/src/registry/model_registry.dart';
1212
import 'package:ht_api/src/services/auth_service.dart';
1313
import 'package:ht_api/src/services/auth_token_service.dart';
14-
// Import the new JWT service
15-
import 'package:ht_api/src/services/jwt_auth_token_service.dart';
14+
// Import the simple service for debugging
15+
import 'package:ht_api/src/services/simple_auth_token_service.dart';
1616
import 'package:ht_api/src/services/verification_code_storage_service.dart';
1717
import 'package:ht_app_settings_inmemory/ht_app_settings_inmemory.dart';
1818
import 'package:ht_app_settings_repository/ht_app_settings_repository.dart';
@@ -186,13 +186,13 @@ Handler middleware(Handler handler) {
186186
emailClient: HtEmailInMemoryClient(),
187187
);
188188
print('[MiddlewareSetup] HtEmailRepository instantiated.'); // Added log
189-
// Auth Services (using JWT and in-memory implementations)
190-
// Instantiate the new JWT service, passing its dependencies
191-
final authTokenService = JwtAuthTokenService(
189+
// Auth Services (using Simple and in-memory implementations for debugging)
190+
// Instantiate the simple service, passing its dependencies
191+
final authTokenService = SimpleAuthTokenService(
192192
userRepository: userRepository,
193-
uuidGenerator: uuid,
193+
// No uuidGenerator needed for SimpleAuthTokenService
194194
);
195-
print('[MiddlewareSetup] JwtAuthTokenService instantiated.'); // Added log
195+
print('[MiddlewareSetup] SimpleAuthTokenService instantiated.'); // Updated log
196196
final verificationCodeStorageService =
197197
InMemoryVerificationCodeStorageService();
198198
print('[MiddlewareSetup] InMemoryVerificationCodeStorageService instantiated.'); // Added log

0 commit comments

Comments
 (0)