login method

Future<User> login({
  1. required String email,
  2. required String password,
})

Log in with the provided email and password.

Implementation

Future<User> login({required String email, required String password}) async {
  final http.Response response;
  try {
    response = await _httpClient.post(
      Uri.parse('$_hostedUri/api/v1/oauth/token'),
      body: json.encode({
        'grant_type': 'password',
        'username': email,
        'password': password,
      }),
    );
  } catch (error) {
    throw MasonApiLoginFailure(message: '$error');
  }

  if (response.statusCode != HttpStatus.ok) {
    final ErrorResponse error;
    try {
      final body = json.decode(response.body) as Map<String, dynamic>;
      error = ErrorResponse.fromJson(body);
    } catch (_) {
      throw const MasonApiLoginFailure(message: _unknownErrorMessage);
    }
    throw MasonApiLoginFailure(
      message: error.message,
      details: error.details,
    );
  }

  final Credentials credentials;
  try {
    credentials = Credentials.fromTokenResponse(
      json.decode(response.body) as Map<String, dynamic>,
    );
    _flushCredentials(credentials);
  } catch (error) {
    throw MasonApiLoginFailure(message: '$error');
  }

  _credentials = credentials;

  try {
    return _currentUser = credentials.toUser();
  } catch (error) {
    throw MasonApiLoginFailure(message: '$error');
  }
}