validateApiHash method

Future<void> validateApiHash(
  1. String apiKey,
  2. String? apiHash
)

this will throw an error if the api key is not valid other wise it will continue without any errors

Implementation

Future<void> validateApiHash(String apiKey, String? apiHash) async {
  if (apiHash == null) {
    throw NotAuthorizedApiKey();
  }
  ApiHashModel? apiHashModel =
      await _apiKeyInfoDatasource.getApiModel(apiKey);
  // get the api key from the database
  // check if the api key exist in the database
  if (apiHashModel == null) {
    throw NoApiKeyFound();
  }
  String secretKeyEncrypted = apiHashModel.apiSecretEncrypted;
  String? apiSecretKey = _encrypter.decrypt(secretKeyEncrypted);
  if (apiSecretKey == null) {
    throw EncryptionException();
  }
  ApiKeyData? data;
  try {
    data = _getApiFromHash(
      apiHash,
      apiSecretKey: apiSecretKey,
    );
  } catch (e) {
    throw NotValidApiKey();
  }

  if (data == null) {
    throw NotAuthorizedApiKey();
  }

  //! here i must validate this api key from the database to make sure that it not expired and it is allowed and stored in the database
  DateTime now = DateTime.now();
  Duration diff = now.difference(data.createdAt);
  if (diff.isNegative) {
    throw NotValidApiKey();
  }
  if (diff.inMicroseconds > _apiHashExpiryAfter.inMicroseconds) {
    throw NotValidApiKey();
  }

  // check if the api key is active
  if (!apiHashModel.active) {
    throw InactiveApiKey();
  }
  // check for the expiration date of the api key
  var apiInfoModel = apiHashModel.toApiKey(_encrypterSecretKey);
  bool expired = apiInfoModel.expired;
  if (expired) {
    throw ExpiredApiKey();
  }
}