execute method

void execute(
  1. dynamic onComplete(
    1. TokenModel? tokenModel
    ),
  2. dynamic onErrorRefreshTokenExpired(
    1. String
    ), {
  3. dynamic forceNewToken = false,
})

Implementation

void execute(Function(TokenModel? tokenModel) onComplete,
    Function(String) onErrorRefreshTokenExpired,
    {forceNewToken = false}) async {
  int? expiredIn = tokenModel?.expressToken?.expiredIn;
  int? requestedAt = tokenModel?.expressToken?.requestedAt;
  if (!forceNewToken && expiredIn != null && requestedAt != null) {
    int nowInMilliseconds = DateTime.now().millisecondsSinceEpoch;
    int lastTokenRequestPlusDelta =
        requestedAt + REQUEST_DELTA_IN_MILLISECONDS;
    bool tokenHasExpired =
        expiredIn < (nowInMilliseconds - lastTokenRequestPlusDelta);
    if (!tokenHasExpired) {
      debugPrint(
          "Y-Auth: GetAccessTokenUseCase:: Token is still valid ${tokenModel}");
      onComplete(tokenModel);
      return;
    } else {
      debugPrint("Y-Auth: GetAccessTokenUseCase: Access Token has expired");
    }
  } else {
    debugPrint(
        "Y-Auth: GetAccessTokenUseCase: First Launch or Access Token has been force to update");
  }

  String refreshToken = await _preferencesDatasource.getRefreshToken();

  if (refreshToken.isNotEmpty) {
    AuthResponse authResponse =
        await _requestAccessTokenUseCase.execute(refreshToken);
    switch (authResponse) {
      case ErrorResponse():
        int statusCode = authResponse.statusCode;
        if (statusCode == 401) {
          _signOutUseCase.execute();
          onErrorRefreshTokenExpired("Refresh Token has expired");
          return;
        }
        break;

      case SuccessResponse():
        try {
          tokenModel = TokenModel.fromJson(json.decode(authResponse.body));
        } catch (e) {
          debugPrint("GetNewAccessToken: Token Model exception: ${e}");
        }
        break;
    }
  } else {
    onErrorRefreshTokenExpired("No Refresh token found");
    return;
  }

  onComplete(tokenModel);
}