Sumitss

Untitled

Apr 29th, 2021
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 2.04 KB | None | 0 0
  1. import 'dart:convert';
  2.  
  3. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  4. import "package:gql_error_link/gql_error_link.dart";
  5. import "package:gql_exec/gql_exec.dart";
  6. import "package:gql_http_link/gql_http_link.dart";
  7. import "package:gql_link/gql_link.dart";
  8. import "package:gql_transform_link/gql_transform_link.dart";
  9. import 'package:hive/hive.dart';
  10.  
  11.  
  12.  
  13. class HttpAuthLink extends Link {
  14.   Link _link = "" as Link; //Link _link ;
  15.   String _token = "" ; //String _token;
  16.  
  17.   HttpAuthLink() {
  18.     _link = Link.concat(
  19.       ErrorLink(onException: handleException),
  20.       TransformLink(requestTransformer: transformRequest),
  21.     );
  22.   }
  23.  
  24.   Future<void> updateToken() async {
  25.     // _token = await Future.delayed(
  26.     //   Duration(milliseconds: 10),
  27.     //       () => "Valid token",
  28.     // );
  29.     final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
  30.     var encryptionKey = base64Url.decode((await secureStorage.read(key: 'key'))!);
  31.     var encryptedBox = await Hive.openBox('auth', encryptionCipher: HiveAesCipher(encryptionKey));
  32.     _token=encryptedBox.get('token');
  33.   }
  34.  
  35.   Stream<Response> handleException(Request request,
  36.       NextLink forward,
  37.       LinkException exception,) async* {
  38.     if (exception is HttpLinkServerException &&
  39.         exception.response.statusCode == 401) {
  40.       await updateToken();
  41.  
  42.       yield* forward(request);
  43.  
  44.       return;
  45.     }
  46.  
  47.     throw exception;
  48.   }
  49.  
  50.   Request transformRequest(Request request) =>
  51.       request.updateContextEntry<HttpLinkHeaders>(
  52.             (headers) =>
  53.             HttpLinkHeaders(
  54.               headers: <String, String>{
  55.                 ...headers?.headers ?? <String, String>{},
  56.                 "Authorization": _token,
  57.               },
  58.             ),
  59.       );
  60.  
  61.   @override
  62.   Stream<Response> request(Request request, [forward]) async* {
  63.     // if (_token == null) {
  64.     //   await updateToken();
  65.     // }
  66.     if (_token == "") {
  67.       await updateToken();
  68.     }
  69.  
  70.     yield* _link.request(request, forward);
  71.   }
  72. }
Add Comment
Please, Sign In to add comment