Testing is complete!! And a nice build runner script to boot
This commit is contained in:
@@ -4,6 +4,7 @@ import 'package:backend/database.dart';
|
||||
import 'package:backend/service/db_access.dart';
|
||||
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:shared_models/jwt.dart';
|
||||
import 'package:shared_models/user.dart';
|
||||
|
||||
final jwtSecret = _getSecret();
|
||||
@@ -18,21 +19,16 @@ enum JWTTokenStatus {
|
||||
}
|
||||
|
||||
class Authenticator {
|
||||
Future<String?> generateToken(CreateUserRequest req) async {
|
||||
Future<(String?, User?)> generateToken(CreateUserRequest req) async {
|
||||
final newUser = await Db.createUser(username: req.username, roomCode: req.roomCode);
|
||||
if (newUser == null) return null;
|
||||
if (newUser == null) return (null, null);
|
||||
|
||||
final iat = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
final jwt = JWT(
|
||||
{
|
||||
'uid': newUser.uuid,
|
||||
'roomUuid': newUser.gameRoomUuid,
|
||||
'iat': iat,
|
||||
'exp': iat + expTimeSecs,
|
||||
},
|
||||
JWTBody(uuid: newUser.uuid, roomUuid: newUser.gameRoomUuid, iat: iat, exp: iat + expTimeSecs).toJson(),
|
||||
);
|
||||
|
||||
return jwt.sign(SecretKey(jwtSecret));
|
||||
return (jwt.sign(SecretKey(jwtSecret)), newUser);
|
||||
}
|
||||
|
||||
Future<(User?, JWTTokenStatus)> verifyToken(
|
||||
@@ -45,18 +41,15 @@ class Authenticator {
|
||||
SecretKey(jwtSecret),
|
||||
);
|
||||
|
||||
final payloadData = payload.payload as Map<String, dynamic>;
|
||||
final jwt = JWTBody.fromJson(payload.payload as Map<String, dynamic>);
|
||||
|
||||
final iat = payloadData['iat'] as int;
|
||||
final exp = payloadData['exp'] as int;
|
||||
|
||||
if (iat + expTimeSecs != exp || DateTime.now().millisecondsSinceEpoch ~/ 1000 > exp) {
|
||||
if (jwt.iat + expTimeSecs != jwt.exp || DateTime.now().millisecondsSinceEpoch ~/ 1000 > jwt.exp) {
|
||||
return (null, JWTTokenStatus.expired);
|
||||
}
|
||||
|
||||
final uuid = payloadData['uuid'] as String;
|
||||
return (await Db.getUser(uuid), JWTTokenStatus.valid);
|
||||
return (await Db.getUserById(jwt.uuid), JWTTokenStatus.valid);
|
||||
} catch (e) {
|
||||
log.fine('Error verifying token', e);
|
||||
return (null, JWTTokenStatus.invalid);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user