Add JWT auth for protected routes, add /reg endpoint, remove /user endpoints
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user