34 lines
947 B
Dart
34 lines
947 B
Dart
import 'dart:io';
|
|
import 'package:backend/extensions/request_context.dart';
|
|
import 'package:dart_frog/dart_frog.dart';
|
|
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
|
|
|
Middleware authMiddleware() {
|
|
return (handler) {
|
|
return (context) async {
|
|
// Get the authorization header
|
|
final authHeader = context.request.headers['authorization'];
|
|
if (authHeader == null || !authHeader.startsWith('Bearer ')) {
|
|
return Response(statusCode: HttpStatus.unauthorized);
|
|
}
|
|
|
|
final token = authHeader.substring(7);
|
|
try {
|
|
// Verify the JWT token
|
|
JWT.verify(
|
|
token,
|
|
SecretKey(jwtSecret),
|
|
);
|
|
|
|
// If verification successful, continue to the route handler
|
|
return handler(context);
|
|
} catch (e) {
|
|
return Response.json(
|
|
statusCode: HttpStatus.unauthorized,
|
|
body: {'error': e.toString()},
|
|
);
|
|
}
|
|
};
|
|
};
|
|
}
|