authenticate method
Authenticate to this CARP service using a username
and password
.
Return the signed in user (with an OAuthToken access token), if successful. Throws a CarpServiceException if not successful.
Implementation
Future<CarpUser> authenticate({
required String username,
required String password,
}) async {
if (_app == null) {
throw CarpServiceException(
message:
"CARP Service not initialized. Call 'CarpService().configure()' first.");
}
_currentUser = CarpUser(username: username);
final loginBody = {
"client_id": _app!.oauth.clientID,
"client_secret": _app!.oauth.clientSecret,
"grant_type": "password",
"scope": "read",
"username": username,
"password": password
};
final http.Response response = await httpr.post(
Uri.encodeFull(authEndpointUri),
headers: _authenticationHeader,
body: loginBody,
);
int httpStatusCode = response.statusCode;
Map<String, dynamic> responseJson =
json.decode(response.body) as Map<String, dynamic>;
if (httpStatusCode == HttpStatus.ok) {
_currentUser!.authenticated(OAuthToken.fromMap(responseJson));
await getCurrentUserProfile();
_authEventController.add(AuthEvent.authenticated);
return _currentUser!;
}
// All other cases are treated as a failed attempt and throws an error
_authEventController.add(AuthEvent.failed);
_currentUser = null;
// auth error response from CARP is on the form
// {error: invalid_grant, error_description: Bad credentials}
throw CarpServiceException(
httpStatus: HTTPStatus(httpStatusCode, response.reasonPhrase),
message: responseJson["error_description"].toString(),
);
}