Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:convert';
- import 'package:flutter_secure_storage/flutter_secure_storage.dart';
- import "package:gql_error_link/gql_error_link.dart";
- import "package:gql_exec/gql_exec.dart";
- import "package:gql_http_link/gql_http_link.dart";
- import "package:gql_link/gql_link.dart";
- import "package:gql_transform_link/gql_transform_link.dart";
- import 'package:hive/hive.dart';
- class HttpAuthLink extends Link {
- Link _link = "" as Link; //Link _link ;
- String _token = "" ; //String _token;
- HttpAuthLink() {
- _link = Link.concat(
- ErrorLink(onException: handleException),
- TransformLink(requestTransformer: transformRequest),
- );
- }
- Future<void> updateToken() async {
- // _token = await Future.delayed(
- // Duration(milliseconds: 10),
- // () => "Valid token",
- // );
- final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
- var encryptionKey = base64Url.decode((await secureStorage.read(key: 'key'))!);
- var encryptedBox = await Hive.openBox('auth', encryptionCipher: HiveAesCipher(encryptionKey));
- _token=encryptedBox.get('token');
- }
- Stream<Response> handleException(Request request,
- NextLink forward,
- LinkException exception,) async* {
- if (exception is HttpLinkServerException &&
- exception.response.statusCode == 401) {
- await updateToken();
- yield* forward(request);
- return;
- }
- throw exception;
- }
- Request transformRequest(Request request) =>
- request.updateContextEntry<HttpLinkHeaders>(
- (headers) =>
- HttpLinkHeaders(
- headers: <String, String>{
- ...headers?.headers ?? <String, String>{},
- "Authorization": _token,
- },
- ),
- );
- @override
- Stream<Response> request(Request request, [forward]) async* {
- // if (_token == null) {
- // await updateToken();
- // }
- if (_token == "") {
- await updateToken();
- }
- yield* _link.request(request, forward);
- }
- }
Add Comment
Please, Sign In to add comment