44 lines
1.1 KiB
Dart
44 lines
1.1 KiB
Dart
import 'package:relic/relic.dart';
|
|
|
|
import 'crypto_service.dart';
|
|
|
|
final userIdProperty = ContextProperty<String>('userId');
|
|
final usernameProperty = ContextProperty<String>('username');
|
|
final userLocalIdProperty = ContextProperty<int>('userLocalId');
|
|
|
|
/// JWT authentication middleware
|
|
final jwtMiddleware = createMiddleware(
|
|
onRequest: (request) {
|
|
final authHeader = request.headers.authorization;
|
|
|
|
if (authHeader is! BearerAuthorizationHeader) {
|
|
return Response.unauthorized(
|
|
body: Body.fromString('Bearer token required'),
|
|
);
|
|
}
|
|
|
|
final payload = AuthService.verifyToken(authHeader.token);
|
|
if (payload == null) {
|
|
return Response.forbidden(
|
|
body: Body.fromString('Invalid or expired token'),
|
|
);
|
|
}
|
|
|
|
final userId = payload['sub'] as String?;
|
|
final username = payload['username'] as String?;
|
|
|
|
if (userId == null) {
|
|
return Response.forbidden(
|
|
body: Body.fromString('Invalid token payload'),
|
|
);
|
|
}
|
|
|
|
userIdProperty[request] = userId;
|
|
if (username != null) {
|
|
usernameProperty[request] = username;
|
|
}
|
|
|
|
return null; // Continue to handler
|
|
},
|
|
);
|