Sumitss

Untitled

Jun 11th, 2021
575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 5.42 KB | None | 0 0
  1. import 'dart:convert';
  2. import 'package:ferry/ferry.dart';
  3. import 'package:flutter_secure_storage/flutter_secure_storage.dart';
  4. import 'package:get_it/get_it.dart';
  5. import "package:gql_error_link/gql_error_link.dart";
  6. import "package:gql_exec/gql_exec.dart";
  7. import "package:gql_http_link/gql_http_link.dart";
  8. import "package:gql_link/gql_link.dart";
  9. import "package:gql_transform_link/gql_transform_link.dart";
  10. import 'package:hive/hive.dart';
  11. import 'package:itemreq/extras.dart';
  12. import 'package:itemreq/graphql/verifyToken.req.gql.dart';
  13. import 'package:itemreq/graphql/refreshToken.req.gql.dart';
  14. import 'package:jwt_decoder/jwt_decoder.dart';
  15.  
  16. class HttpAuthLink extends Link {
  17.   late Link _link;
  18.   String? _token;
  19.   String? _refreshToken;
  20.   bool tokenState = true;
  21.   late Request req;
  22.   // if (JwtDecoder.isExpired(_token!)) {
  23.   //       // print("Token is expired");
  24.   //       await updateToken();
  25.   //     }
  26.   HttpAuthLink() {
  27.     // _token= initializer()[1];
  28.     // _refreshToken = initializer()[0];
  29.     print("You are in HTTP Auth link");
  30.     _link = Link.concat(
  31.       ErrorLink(onException: handleException),
  32.       TransformLink(requestTransformer: transformRequest),
  33.     );
  34.   }
  35.  
  36.   Future<void> updateToken() async {
  37.     print("You have entered for token updation");
  38.     final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
  39.     var containsAuthEncryptionKey =
  40.         await secureStorage.containsKey(key: 'AuthKey');
  41.     if (containsAuthEncryptionKey) {
  42.       var authEncryptionKey =
  43.           base64Url.decode((await secureStorage.read(key: 'AuthKey'))!);
  44.       var encryptedAuthBox = await Hive.openBox('AuthBox',
  45.           encryptionCipher: HiveAesCipher(authEncryptionKey));
  46.       _token = encryptedAuthBox.get('AuthAccessToken');
  47.       _refreshToken = encryptedAuthBox.get('AuthRefreshToken');
  48.       final verifyReq = GVerifyTokenAPIReq((b) => b..vars.token = _token);
  49.       final client = GetIt.instance<Client>(instanceName: 'client');
  50.       // print("refreshtoken : " + _refreshToken);
  51.       client.request(verifyReq).listen((response) async {
  52.         if (response.hasErrors) {
  53.           tokenState = false;
  54.           print("An error occurs");
  55.           print(response.operationRequest);
  56.           print(response.linkException);
  57.           print(response.graphqlErrors);
  58.           if (!tokenState) {
  59.             final refreshReq =
  60.                 GRefreshTokenAPIReq((b) => b..vars.refresh = _refreshToken);
  61.             final client1 = GetIt.instance<Client>(instanceName: 'client');
  62.             client1.request(refreshReq).listen((response1) async {
  63.               if (response1.hasErrors) {
  64.                 print(response1.operationRequest);
  65.                 print("------------------------");
  66.                 print(response1.linkException);
  67.                 movetologin();
  68.               } else {
  69.                 _token = response1.data!.refreshToken!.token!;
  70.                 _refreshToken = response1.data!.refreshToken!.refreshToken!;
  71.                 try {
  72.                   final FlutterSecureStorage secureStorage =
  73.                       const FlutterSecureStorage();
  74.                   var containsEncryptionKey =
  75.                       await secureStorage.containsKey(key: 'AuthKey');
  76.                   if (!containsEncryptionKey) {
  77.                     var key = Hive.generateSecureKey();
  78.                     await secureStorage.write(
  79.                         key: 'AuthKey', value: base64UrlEncode(key));
  80.                   }
  81.                   var encryptionKey = base64Url
  82.                       .decode((await secureStorage.read(key: 'AuthKey'))!);
  83.                   var encryptedBox = await Hive.openBox('AuthBox',
  84.                       encryptionCipher: HiveAesCipher(encryptionKey));
  85.                   await encryptedBox.put('AuthAccessToken', _token);
  86.                   await encryptedBox.put("AuthRefreshToken", _refreshToken);
  87.                 } on Exception catch (e) {
  88.                   throw Exception(e.toString());
  89.                 }
  90.               }
  91.             });
  92.           }
  93.         } else if (response.data!.verifyToken!.errors == null) {
  94.           print("Token verified");
  95.         } else {
  96.           print("----------There occur an error------------");
  97.         }
  98.       });
  99.     } else {
  100.       return null;
  101.     }
  102.   }
  103.  
  104.   Stream<Response> handleException(
  105.     Request request,
  106.     NextLink forward,
  107.     LinkException exception,
  108.   ) async* {
  109.     if ((exception is HttpLinkServerException &&
  110.             exception.response.statusCode == 401) ||
  111.         exception is GraphQLError) {
  112.       await updateToken();
  113.  
  114.       yield* forward(request);
  115.  
  116.       return;
  117.     }
  118.  
  119.     throw exception;
  120.   }
  121.  
  122.   Future<Request> transformRequest(Request request) async {
  123.     var updatedRequest = request.updateContextEntry<HttpLinkHeaders>(
  124.       (headers) => HttpLinkHeaders(
  125.         headers: <String, String>{
  126.           ...headers?.headers ?? <String, String>{},
  127.         },
  128.       ),
  129.     );
  130.  
  131.     if (_token != null) {
  132.       updatedRequest = request.updateContextEntry<HttpLinkHeaders>(
  133.         (headers) => HttpLinkHeaders(
  134.           headers: <String, String>{
  135.             "AUTHORIZATION": "JWT " + _token!,
  136.           },
  137.         ),
  138.       );
  139.     }
  140.  
  141.     return updatedRequest;
  142.   }
  143.  
  144.   @override
  145.   Stream<Response> request(Request request, [forward]) async* {
  146.     if (_token == null) {
  147.       await updateToken();
  148.     }
  149.     yield* _link.request(request, forward);
  150.   }
  151. }
  152.  
Add Comment
Please, Sign In to add comment