defaultAuthenticationDataParser static method

AuthenticationDataModel? defaultAuthenticationDataParser(
  1. String encodedData, {
  2. bool required = true,
})

If required is set to true, this will throw an exception if AuthenticationDataModel cannot be extracted from given data

Implementation

static AuthenticationDataModel? defaultAuthenticationDataParser(
  String encodedData, {
  bool required = true,
}) {
  AuthenticationDataModel? authData;
  Map<String, dynamic> data = jsonDecode(encodedData);

  if (data.containsKey("data") && !data.containsKey("token")) {
    data = data["data"];
  }
  final String? token = data["token"];
  final String? refreshToken = data["refreshToken"];
  final user = data["user"];

  String? id = data["id"];

  if (id == null && required) {
    // debugPrint("$id");
    if (token == null) {
      throw Exception(
          "Could not retrieve 'token' from response, response was: $encodedData");
    }
    // if null let's try to get it from token
    final splited = token.split(".");
    final payload = splited[1];

    final metadataJson = base64Decode(payload).toString();
    final data = jsonDecode(metadataJson);
    final id = data["id"];
    if (id == null) {
      throw Exception(
          "Could not retrieve user 'id' from response, response was: $encodedData");
    }
  } else if ((id is double || id is int) && required) {
    id = id.toString();
  } else if (id is! String && required) {
    throw Exception(
        "Invalid response, could not parse AuthenticationData, response was: $encodedData");
  }

  if (id != null && token != null) {
    authData = AuthenticationDataModel(
      id: id,
      token: token,
      refreshToken: refreshToken,
      user: user,
    );
  } else if (required) {
    throw Exception(
        "Invalid response, could not parse AuthenticationData, response was: $encodedData");
  }

  return authData;
}