Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:convert';
- import 'package:ferry/ferry.dart';
- import 'package:flutter_secure_storage/flutter_secure_storage.dart';
- import 'package:get_it/get_it.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';
- import 'package:itemreq/extras.dart';
- import 'package:itemreq/graphql/verifyToken.req.gql.dart';
- import 'package:itemreq/graphql/refreshToken.req.gql.dart';
- import 'package:jwt_decoder/jwt_decoder.dart';
- class HttpAuthLink extends Link {
- late Link _link;
- String? _token;
- String? _refreshToken;
- bool tokenState = true;
- late Request req;
- // if (JwtDecoder.isExpired(_token!)) {
- // // print("Token is expired");
- // await updateToken();
- // }
- HttpAuthLink() {
- // _token= initializer()[1];
- // _refreshToken = initializer()[0];
- print("You are in HTTP Auth link");
- _link = Link.concat(
- ErrorLink(onException: handleException),
- TransformLink(requestTransformer: transformRequest),
- );
- }
- Future<void> updateToken() async {
- print("You have entered for token updation");
- final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
- var containsAuthEncryptionKey =
- await secureStorage.containsKey(key: 'AuthKey');
- if (containsAuthEncryptionKey) {
- var authEncryptionKey =
- base64Url.decode((await secureStorage.read(key: 'AuthKey'))!);
- var encryptedAuthBox = await Hive.openBox('AuthBox',
- encryptionCipher: HiveAesCipher(authEncryptionKey));
- _token = encryptedAuthBox.get('AuthAccessToken');
- _refreshToken = encryptedAuthBox.get('AuthRefreshToken');
- final verifyReq = GVerifyTokenAPIReq((b) => b..vars.token = _token);
- final client = GetIt.instance<Client>(instanceName: 'client');
- // print("refreshtoken : " + _refreshToken);
- client.request(verifyReq).listen((response) async {
- if (response.hasErrors) {
- tokenState = false;
- print("An error occurs");
- print(response.operationRequest);
- print(response.linkException);
- print(response.graphqlErrors);
- if (!tokenState) {
- final refreshReq =
- GRefreshTokenAPIReq((b) => b..vars.refresh = _refreshToken);
- final client1 = GetIt.instance<Client>(instanceName: 'client');
- client1.request(refreshReq).listen((response1) async {
- if (response1.hasErrors) {
- print(response1.operationRequest);
- print("------------------------");
- print(response1.linkException);
- movetologin();
- } else {
- _token = response1.data!.refreshToken!.token!;
- _refreshToken = response1.data!.refreshToken!.refreshToken!;
- try {
- final FlutterSecureStorage secureStorage =
- const FlutterSecureStorage();
- var containsEncryptionKey =
- await secureStorage.containsKey(key: 'AuthKey');
- if (!containsEncryptionKey) {
- var key = Hive.generateSecureKey();
- await secureStorage.write(
- key: 'AuthKey', value: base64UrlEncode(key));
- }
- var encryptionKey = base64Url
- .decode((await secureStorage.read(key: 'AuthKey'))!);
- var encryptedBox = await Hive.openBox('AuthBox',
- encryptionCipher: HiveAesCipher(encryptionKey));
- await encryptedBox.put('AuthAccessToken', _token);
- await encryptedBox.put("AuthRefreshToken", _refreshToken);
- } on Exception catch (e) {
- throw Exception(e.toString());
- }
- }
- });
- }
- } else if (response.data!.verifyToken!.errors == null) {
- print("Token verified");
- } else {
- print("----------There occur an error------------");
- }
- });
- } else {
- return null;
- }
- }
- Stream<Response> handleException(
- Request request,
- NextLink forward,
- LinkException exception,
- ) async* {
- if ((exception is HttpLinkServerException &&
- exception.response.statusCode == 401) ||
- exception is GraphQLError) {
- await updateToken();
- yield* forward(request);
- return;
- }
- throw exception;
- }
- Future<Request> transformRequest(Request request) async {
- var updatedRequest = request.updateContextEntry<HttpLinkHeaders>(
- (headers) => HttpLinkHeaders(
- headers: <String, String>{
- ...headers?.headers ?? <String, String>{},
- },
- ),
- );
- if (_token != null) {
- updatedRequest = request.updateContextEntry<HttpLinkHeaders>(
- (headers) => HttpLinkHeaders(
- headers: <String, String>{
- "AUTHORIZATION": "JWT " + _token!,
- },
- ),
- );
- }
- return updatedRequest;
- }
- @override
- Stream<Response> request(Request request, [forward]) async* {
- if (_token == null) {
- await updateToken();
- }
- yield* _link.request(request, forward);
- }
- }
Add Comment
Please, Sign In to add comment