29 lines
823 B
Dart
29 lines
823 B
Dart
import 'package:shelf/shelf.dart';
|
|
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
|
import 'package:dotenv/dotenv.dart';
|
|
|
|
class AuthMiddleware {
|
|
final Handler handler;
|
|
|
|
AuthMiddleware(this.handler);
|
|
|
|
Future<Response> call(Request request) async {
|
|
final authorization = request.headers['authorization'];
|
|
|
|
if (authorization == null || !authorization.startsWith('Bearer ')) {
|
|
return Response(401, body: 'Authorization header missing or invalid');
|
|
}
|
|
|
|
final token = authorization.substring(7);
|
|
|
|
try {
|
|
final dotenv = DotEnv();
|
|
final secret = dotenv['JWT_SECRET'] ?? '';
|
|
final decoded = JWT.verify(token, SecretKey(secret));
|
|
|
|
return handler(request);
|
|
} catch (e) {
|
|
return Response(401, body: 'Invalid or expired token');
|
|
}
|
|
}
|
|
} |