Mostly working websocket stuff, some message weirdness at the moment...
This commit is contained in:
@@ -3,6 +3,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:frontend/providers/auth.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shared_models/jwt.dart';
|
||||
|
||||
part 'dio.g.dart';
|
||||
|
||||
@@ -17,8 +18,13 @@ Dio dio(Ref ref) {
|
||||
));
|
||||
|
||||
final jwt = ref.watch(jwtNotifierProvider).valueOrNull;
|
||||
final jwtBody = ref.read(jwtBodyProvider);
|
||||
|
||||
dio.interceptors.addAll([JwtInterceptor(jwt: jwt), CustomLogInterceptor()]);
|
||||
dio.interceptors.addAll([
|
||||
JwtInterceptor(
|
||||
jwt: jwt, jwtBody: jwtBody, invalidateJwtCallback: () => ref.read(jwtNotifierProvider.notifier).eraseJwt()),
|
||||
CustomLogInterceptor()
|
||||
]);
|
||||
|
||||
logger.fine('Created new Dio object');
|
||||
|
||||
@@ -28,15 +34,36 @@ Dio dio(Ref ref) {
|
||||
// Adds the jwt to
|
||||
class JwtInterceptor extends Interceptor {
|
||||
final String? jwt;
|
||||
final JWTBody? jwtBody;
|
||||
final Function invalidateJwtCallback;
|
||||
|
||||
JwtInterceptor({required this.jwt});
|
||||
JwtInterceptor({required this.jwt, required this.jwtBody, required this.invalidateJwtCallback});
|
||||
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
||||
if (jwt == null || jwtBody == null) {
|
||||
handler.next(options);
|
||||
return;
|
||||
}
|
||||
if (jwtBody != null && jwtBody!.exp < DateTime.now().millisecondsSinceEpoch ~/ 1000) {
|
||||
invalidateJwtCallback();
|
||||
handler.next(options);
|
||||
return;
|
||||
}
|
||||
if (jwt != null) {
|
||||
options.headers['Authorization'] = 'Bearer $jwt';
|
||||
handler.next(options);
|
||||
}
|
||||
handler.next(options);
|
||||
}
|
||||
|
||||
// on unauthorized request, remove jwt
|
||||
@override
|
||||
// ignore: strict_raw_type
|
||||
void onResponse(Response response, ResponseInterceptorHandler handler) {
|
||||
if (response.statusCode == 401) {
|
||||
invalidateJwtCallback();
|
||||
}
|
||||
handler.next(response);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user