Skip to content

Commit 0820116

Browse files
committed
style: misc
1 parent a70acec commit 0820116

14 files changed

+114
-175
lines changed

lib/src/middlewares/authentication_middleware.dart

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -21,41 +21,27 @@ Middleware authenticationProvider() {
2121
// Read the interface type
2222
AuthTokenService tokenService;
2323
try {
24-
print(
25-
'[AuthMiddleware] Attempting to read AuthTokenService...',
26-
);
24+
print('[AuthMiddleware] Attempting to read AuthTokenService...');
2725
tokenService = context.read<AuthTokenService>();
28-
print(
29-
'[AuthMiddleware] Successfully read AuthTokenService.',
30-
);
26+
print('[AuthMiddleware] Successfully read AuthTokenService.');
3127
} catch (e, s) {
32-
print(
33-
'[AuthMiddleware] FAILED to read AuthTokenService: $e\n$s',
34-
);
28+
print('[AuthMiddleware] FAILED to read AuthTokenService: $e\n$s');
3529
// Re-throw the error to be caught by the main error handler
3630
rethrow;
3731
}
3832
User? user;
3933

4034
// Extract the Authorization header
41-
print(
42-
'[AuthMiddleware] Attempting to read Authorization header...',
43-
);
35+
print('[AuthMiddleware] Attempting to read Authorization header...');
4436
final authHeader = context.request.headers['Authorization'];
45-
print(
46-
'[AuthMiddleware] Authorization header value: $authHeader',
47-
);
37+
print('[AuthMiddleware] Authorization header value: $authHeader');
4838

4939
if (authHeader != null && authHeader.startsWith('Bearer ')) {
5040
// Extract the token string
5141
final token = authHeader.substring(7); // Length of 'Bearer '
52-
print(
53-
'[AuthMiddleware] Extracted Bearer token.',
54-
);
42+
print('[AuthMiddleware] Extracted Bearer token.');
5543
try {
56-
print(
57-
'[AuthMiddleware] Attempting to validate token...',
58-
);
44+
print('[AuthMiddleware] Attempting to validate token...');
5945
// Validate the token using the service
6046
user = await tokenService.validateToken(token);
6147
print(
@@ -118,9 +104,7 @@ Middleware requireAuthentication() {
118104
}
119105
// If user exists, proceed to the handler
120106
print('Authentication check passed for user: ${user.id}');
121-
return handler(
122-
context.provide<User>(() => user),
123-
);
107+
return handler(context.provide<User>(() => user));
124108
};
125109
};
126110
}

lib/src/middlewares/authorization_middleware.dart

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ Middleware authorizationMiddleware() {
2828
final user = context.read<User>();
2929
final permissionService = context.read<PermissionService>();
3030
final modelName = context.read<String>(); // Provided by data/_middleware
31-
final modelConfig =
32-
context.read<ModelConfig<dynamic>>(); // Provided by data/_middleware
31+
final modelConfig = context
32+
.read<ModelConfig<dynamic>>(); // Provided by data/_middleware
3333
final method = context.request.method;
3434

3535
// Determine if the request is for the collection or an item

lib/src/middlewares/error_handler.dart

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,7 @@ Middleware errorHandler() {
2323
return Response.json(
2424
statusCode: statusCode,
2525
body: {
26-
'error': {
27-
'code': errorCode,
28-
'message': e.message,
29-
},
26+
'error': {'code': errorCode, 'message': e.message},
3027
},
3128
);
3229
} on FormatException catch (e, stackTrace) {

lib/src/rbac/role_permissions.dart

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,7 @@ final Set<String> _standardUserPermissions = {
2323

2424
// For now, premium users have the same permissions as standard users,
2525
// but this set can be expanded later for premium-specific features.
26-
final Set<String> _premiumUserPermissions = {
27-
..._standardUserPermissions,
28-
};
26+
final Set<String> _premiumUserPermissions = {..._standardUserPermissions};
2927

3028
final Set<String> _adminPermissions = {
3129
..._standardUserPermissions,

lib/src/registry/model_registry.dart

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ class ModelActionPermission {
3030
this.permission,
3131
this.requiresOwnershipCheck = false,
3232
}) : assert(
33-
type != RequiredPermissionType.specificPermission ||
34-
permission != null,
35-
'Permission string must be provided for specificPermission type',
36-
);
33+
type != RequiredPermissionType.specificPermission ||
34+
permission != null,
35+
'Permission string must be provided for specificPermission type',
36+
);
3737

3838
/// The type of permission check required.
3939
final RequiredPermissionType type;
@@ -265,8 +265,9 @@ final modelRegistry = <String, ModelConfig<dynamic>>{
265265
'user_content_preferences': ModelConfig<UserContentPreferences>(
266266
fromJson: UserContentPreferences.fromJson,
267267
getId: (p) => p.id,
268-
getOwnerId: (dynamic item) => (item as UserContentPreferences).id
269-
as String?, // User ID is the owner ID
268+
getOwnerId: (dynamic item) =>
269+
(item as UserContentPreferences).id
270+
as String?, // User ID is the owner ID
270271
getCollectionPermission: const ModelActionPermission(
271272
type: RequiredPermissionType.unsupported, // Not accessible via collection
272273
),
@@ -322,6 +323,4 @@ typedef ModelRegistryMap = Map<String, ModelConfig<dynamic>>;
322323
/// This makes the `modelRegistry` map available for injection into the
323324
/// request context via `context.read<ModelRegistryMap>()`. It's primarily
324325
/// used by the middleware in `routes/api/v1/data/_middleware.dart`.
325-
final modelRegistryProvider = provider<ModelRegistryMap>(
326-
(_) => modelRegistry,
327-
);
326+
final modelRegistryProvider = provider<ModelRegistryMap>((_) => modelRegistry);

lib/src/services/auth_service.dart

Lines changed: 29 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,23 @@ class AuthService {
2020
required HtEmailRepository emailRepository,
2121
required HtDataRepository<UserAppSettings> userAppSettingsRepository,
2222
required HtDataRepository<UserContentPreferences>
23-
userContentPreferencesRepository,
23+
userContentPreferencesRepository,
2424
required Uuid uuidGenerator,
25-
}) : _userRepository = userRepository,
26-
_authTokenService = authTokenService,
27-
_verificationCodeStorageService = verificationCodeStorageService,
28-
_emailRepository = emailRepository,
29-
_userAppSettingsRepository = userAppSettingsRepository,
30-
_userContentPreferencesRepository = userContentPreferencesRepository,
31-
_uuid = uuidGenerator;
25+
}) : _userRepository = userRepository,
26+
_authTokenService = authTokenService,
27+
_verificationCodeStorageService = verificationCodeStorageService,
28+
_emailRepository = emailRepository,
29+
_userAppSettingsRepository = userAppSettingsRepository,
30+
_userContentPreferencesRepository = userContentPreferencesRepository,
31+
_uuid = uuidGenerator;
3232

3333
final HtDataRepository<User> _userRepository;
3434
final AuthTokenService _authTokenService;
3535
final VerificationCodeStorageService _verificationCodeStorageService;
3636
final HtEmailRepository _emailRepository;
3737
final HtDataRepository<UserAppSettings> _userAppSettingsRepository;
3838
final HtDataRepository<UserContentPreferences>
39-
_userContentPreferencesRepository;
39+
_userContentPreferencesRepository;
4040
final Uuid _uuid;
4141

4242
/// Initiates the email sign-in process.
@@ -47,16 +47,11 @@ class AuthService {
4747
Future<void> initiateEmailSignIn(String email) async {
4848
try {
4949
// Generate and store the code for standard sign-in
50-
final code =
51-
await _verificationCodeStorageService.generateAndStoreSignInCode(
52-
email,
53-
);
50+
final code = await _verificationCodeStorageService
51+
.generateAndStoreSignInCode(email);
5452

5553
// Send the code via email
56-
await _emailRepository.sendOtpEmail(
57-
recipientEmail: email,
58-
otpCode: code,
59-
);
54+
await _emailRepository.sendOtpEmail(recipientEmail: email, otpCode: code);
6055
print('Initiated email sign-in for $email, code sent.');
6156
} on HtHttpException {
6257
// Propagate known exceptions from dependencies
@@ -83,11 +78,8 @@ class AuthService {
8378
// User? currentAuthUser, // Parameter for potential future linking logic
8479
) async {
8580
// 1. Validate the code for standard sign-in
86-
final isValidCode =
87-
await _verificationCodeStorageService.validateSignInCode(
88-
email,
89-
code,
90-
);
81+
final isValidCode = await _verificationCodeStorageService
82+
.validateSignInCode(email, code);
9183
if (!isValidCode) {
9284
throw const InvalidInputException(
9385
'Invalid or expired verification code.',
@@ -312,11 +304,11 @@ class AuthService {
312304
// 2. Generate and store the link code.
313305
// The storage service itself might throw ConflictException if emailToLink
314306
// is pending for another user or if this user has a pending code.
315-
final code =
316-
await _verificationCodeStorageService.generateAndStoreLinkCode(
317-
userId: anonymousUser.id,
318-
emailToLink: emailToLink,
319-
);
307+
final code = await _verificationCodeStorageService
308+
.generateAndStoreLinkCode(
309+
userId: anonymousUser.id,
310+
emailToLink: emailToLink,
311+
);
320312

321313
// 3. Send the code via email
322314
await _emailRepository.sendOtpEmail(
@@ -359,11 +351,11 @@ class AuthService {
359351

360352
try {
361353
// 1. Validate the link code and retrieve the email that was being linked.
362-
final linkedEmail =
363-
await _verificationCodeStorageService.validateAndRetrieveLinkedEmail(
364-
userId: anonymousUser.id,
365-
linkCode: codeFromUser,
366-
);
354+
final linkedEmail = await _verificationCodeStorageService
355+
.validateAndRetrieveLinkedEmail(
356+
userId: anonymousUser.id,
357+
linkCode: codeFromUser,
358+
);
367359

368360
if (linkedEmail == null) {
369361
throw const InvalidInputException(
@@ -446,9 +438,7 @@ class AuthService {
446438
// 2. Clear any pending verification codes for this user ID (linking).
447439
try {
448440
await _verificationCodeStorageService.clearLinkCode(userId);
449-
print(
450-
'[AuthService] Cleared link code for user ${userToDelete.id}.',
451-
);
441+
print('[AuthService] Cleared link code for user ${userToDelete.id}.');
452442
} catch (e) {
453443
// Log but don't fail deletion if clearing codes fails
454444
print(
@@ -459,8 +449,9 @@ class AuthService {
459449
// 3. Clear any pending sign-in codes for the user's email (if they had one).
460450
if (userToDelete.email != null) {
461451
try {
462-
await _verificationCodeStorageService
463-
.clearSignInCode(userToDelete.email!);
452+
await _verificationCodeStorageService.clearSignInCode(
453+
userToDelete.email!,
454+
);
464455
print(
465456
'[AuthService] Cleared sign-in code for email ${userToDelete.email}.',
466457
);
@@ -488,9 +479,7 @@ class AuthService {
488479
} catch (e) {
489480
// Catch unexpected errors during orchestration
490481
print('Error during deleteAccount for user $userId: $e');
491-
throw OperationFailedException(
492-
'Failed to delete user account: $e',
493-
);
482+
throw OperationFailedException('Failed to delete user account: $e');
494483
}
495484
}
496485
}

lib/src/services/default_user_preference_limit_service.dart

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,7 @@ class DefaultUserPreferenceLimitService implements UserPreferenceLimitService {
6969
rethrow;
7070
} catch (e) {
7171
// Catch unexpected errors
72-
print(
73-
'Error checking limit for user ${user.id}, itemType $itemType: $e',
74-
);
72+
print('Error checking limit for user ${user.id}, itemType $itemType: $e');
7573
throw const OperationFailedException(
7674
'Failed to check user preference limits.',
7775
);
@@ -137,9 +135,7 @@ class DefaultUserPreferenceLimitService implements UserPreferenceLimitService {
137135
rethrow;
138136
} catch (e) {
139137
// Catch unexpected errors
140-
print(
141-
'Error checking update limits for user ${user.id}: $e',
142-
);
138+
print('Error checking update limits for user ${user.id}: $e');
143139
throw const OperationFailedException(
144140
'Failed to check user preference update limits.',
145141
);

lib/src/services/jwt_auth_token_service.dart

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ class JwtAuthTokenService implements AuthTokenService {
3333
required HtDataRepository<User> userRepository,
3434
required TokenBlacklistService blacklistService,
3535
required Uuid uuidGenerator,
36-
}) : _userRepository = userRepository,
37-
_blacklistService = blacklistService,
38-
_uuid = uuidGenerator;
36+
}) : _userRepository = userRepository,
37+
_blacklistService = blacklistService,
38+
_uuid = uuidGenerator;
3939

4040
final HtDataRepository<User> _userRepository;
4141
final TokenBlacklistService _blacklistService;
@@ -68,7 +68,6 @@ class JwtAuthTokenService implements AuthTokenService {
6868
'iat': now.millisecondsSinceEpoch ~/ 1000, // Issued At
6969
'iss': _issuer, // Issuer
7070
'jti': _uuid.v4(), // JWT ID (for potential blacklisting)
71-
7271
// Custom claims (optional, include what's useful)
7372
'email': user.email,
7473
'role': _userRoleToString(
@@ -246,8 +245,10 @@ class JwtAuthTokenService implements AuthTokenService {
246245
'Cannot invalidate token: Missing or invalid expiry (exp) claim.',
247246
);
248247
}
249-
final expiryDateTime =
250-
DateTime.fromMillisecondsSinceEpoch(expClaim * 1000, isUtc: true);
248+
final expiryDateTime = DateTime.fromMillisecondsSinceEpoch(
249+
expClaim * 1000,
250+
isUtc: true,
251+
);
251252
print('[invalidateToken] Extracted expiry: $expiryDateTime');
252253

253254
// 4. Add JTI to the blacklist

lib/src/services/simple_auth_token_service.dart

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ import 'package:ht_shared/ht_shared.dart';
1010
/// {@endtemplate}
1111
class SimpleAuthTokenService implements AuthTokenService {
1212
/// {@macro simple_auth_token_service}
13-
const SimpleAuthTokenService({
14-
required HtDataRepository<User> userRepository,
15-
}) : _userRepository = userRepository;
13+
const SimpleAuthTokenService({required HtDataRepository<User> userRepository})
14+
: _userRepository = userRepository;
1615

1716
final HtDataRepository<User> _userRepository;
1817
static const String _tokenPrefix = 'valid-token-for-user-id:';

lib/src/services/token_blacklist_service.dart

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,7 @@ class InMemoryTokenBlacklistService implements TokenBlacklistService {
9494
print(
9595
'[InMemoryTokenBlacklistService] Error adding jti $jti to store: $e',
9696
);
97-
throw OperationFailedException(
98-
'Failed to add token to blacklist: $e',
99-
);
97+
throw OperationFailedException('Failed to add token to blacklist: $e');
10098
}
10199
}
102100

@@ -127,9 +125,7 @@ class InMemoryTokenBlacklistService implements TokenBlacklistService {
127125
print(
128126
'[InMemoryTokenBlacklistService] Error checking blacklist for jti $jti: $e',
129127
);
130-
throw OperationFailedException(
131-
'Failed to check token blacklist: $e',
132-
);
128+
throw OperationFailedException('Failed to check token blacklist: $e');
133129
}
134130
}
135131

0 commit comments

Comments
 (0)