oauthLogin method

Future<String?> oauthLogin({
  1. required String username,
  2. required String password,
  3. String host = "https://hosting.wialon.com",
})

Login into Wialon using username and password through OAuth, this method will return an Access Token

Implementation

Future<String?> oauthLogin({
  required String username,
  required String password,
  String host = "https://hosting.wialon.com",
}) async {
  Map<String, String> headers = {
    'origin': host,
  };
  String urlToGetSign = "$host/login.html?"
      "client_id=Layrz External Accounts"
      "&access_type=-1"
      "&activation_time=0"
      "&duration=0"
      "&flags=0x1";

  Uri uri = Uri.parse(urlToGetSign);
  http.Response signGetter = await http.get(uri, headers: headers);
  Document page = parser.parse(signGetter.body);
  List<Element> elements = page.getElementsByTagName("input");

  String? sign;
  for (Element element in elements) {
    if (element.attributes["name"] == "sign") {
      sign = element.attributes["value"];
      break;
    }
  }

  if (sign == null) {
    throw SdkException(message: "Sign not found");
  }

  print(sign);

  Map<String, String> request = {
    'response_type': 'token',
    'wialon_sdk_url': 'https://hst-api.wialon.com',
    'client_id': username,
    'access_type': '-1',
    'activation_time': '0',
    'duration': '0',
    'flags': '7',
    'login': username,
    'passw': password,
    'sign': sign,
    'redirect_uri': '$host/post_token.html',
  };

  uri = Uri.parse("https://hosting.wialon.com/oauth.html");
  http.Client client = http.Client();
  http.StreamedResponse redirectGetter = await client.send(http.Request("POST", uri)
    ..bodyFields = request
    ..headers.addAll(headers));
  String? redirect = redirectGetter.headers['location'];

  if (redirect == null) {
    throw SdkException(message: "Redirect url not found");
  }

  uri = Uri.parse(redirect);
  http.StreamedResponse authGetter = await client.send(
    http.Request("GET", uri)
      ..headers.addAll(headers)
      ..followRedirects = false,
  );
  String? responseUrl = authGetter.headers['location'];
  if (responseUrl == null) {
    throw SdkException(message: "Response url not found");
  }

  responseUrl = responseUrl.split("?").last;
  Map<String, dynamic> responseMap = Uri.splitQueryString(responseUrl);
  String? token = responseMap['access_token'];
  return token;
}