requestToken method

  1. @override
Future<String> requestToken(
  1. String username,
  2. String password
)
override

Requests a token the given username and password.

Returns a Future that resolves to a String containing the authentication token.

Implementation

@override
Future<String> requestToken(String username, String password) async {
  log.info("Requesting token for user $username");

  final url =
      "${config.kMoodleServerAdress}/login/token.php?service=$webService&moodlewsrestformat=json";

  var response = await networkService.post(
    url,
    body: {
      "username": username,
      "password": password,
      "moodlewsrestformat": "json",
      "service": webService,
    },
    headers: {"Content-Type": "application/x-www-form-urlencoded"},
  );

  if (response.statusCode == 200) {
    log.info("Token request successful");

    final body = response.body as JSON;

    final token = body["token"];

    if (token == null) {
      log.severe("Token request failed: $body");

      throw Exception("Failed to request token: $body");
    }

    return token;
  }

  log.severe(
      "Token request failed with status code ${response.statusCode}, body: ${response.body}");

  throw Exception("Failed to request token");
}