WIP auth, added Drift for database and refined shared_models for data exchange
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
import 'package:backend/authenticator.dart';
|
||||
import 'package:backend/database.dart';
|
||||
import 'package:dart_frog/dart_frog.dart';
|
||||
import 'package:dart_frog_auth/dart_frog_auth.dart';
|
||||
|
||||
Handler middleware(Handler handler) {
|
||||
return handler.use(
|
||||
bearerAuthentication<User>(
|
||||
authenticator: (context, token) async {
|
||||
final authenticator = context.read<Authenticator>();
|
||||
return authenticator.verifyToken(token);
|
||||
},
|
||||
// says to apply the middleware to all routes
|
||||
applies: (_) async => true,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import 'package:dart_frog/dart_frog.dart';
|
||||
|
||||
Response onRequest(RequestContext context, String roomCode) {
|
||||
return Response(body: 'Joined $roomCode!');
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// lib/routes/tasks/_middleware.dart
|
||||
import 'package:dart_frog/dart_frog.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
final log = Logger('');
|
||||
|
||||
Handler middleware(Handler handler) {
|
||||
return handler.use(
|
||||
(handler) => (context) async {
|
||||
final request = context.request;
|
||||
log.info('${request.method.value} ${request.uri.path}');
|
||||
return await handler(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:backend/authenticator.dart';
|
||||
import 'package:dart_frog/dart_frog.dart';
|
||||
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
||||
import 'package:shared_models/user.dart';
|
||||
|
||||
Future<Response> onRequest(RequestContext context) async {
|
||||
// Only allow POST requests
|
||||
if (context.request.method != HttpMethod.post) {
|
||||
return Response(statusCode: HttpStatus.methodNotAllowed);
|
||||
}
|
||||
|
||||
try {
|
||||
// Parse the request body
|
||||
final body = await context.request.json() as Map<String, dynamic>;
|
||||
final createUserReq = CreateUserRequest.fromJson(body);
|
||||
|
||||
// Generate token
|
||||
final authenticator = context.read<Authenticator>();
|
||||
final token = await authenticator.generateToken(username: createUserReq.username);
|
||||
|
||||
if (token == null) {
|
||||
return Response.json(
|
||||
statusCode: HttpStatus.internalServerError,
|
||||
body: {'error': 'Failed to generate token'},
|
||||
);
|
||||
}
|
||||
|
||||
// Return the token
|
||||
return Response.json(
|
||||
body: {'token': token},
|
||||
);
|
||||
} on JWTParseException {
|
||||
return Response.json(
|
||||
statusCode: HttpStatus.badRequest,
|
||||
body: {'error': 'Username is required'},
|
||||
);
|
||||
} catch (e) {
|
||||
return Response.json(
|
||||
statusCode: HttpStatus.internalServerError,
|
||||
body: {'error': 'Internal server error'},
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user