hostedCodeLogin method
Completes the hosted signin process with the hostedCode
and sets the API user.
Implementation
Future<void> hostedCodeLogin(String hostedCode) async {
if (!config.cognitoEnabled) {
throw StateError('Cannot login with Cognito disabled.');
}
final endpoint = Uri.parse(config.cognitoEndpoint!);
final url = endpoint.resolve("/oauth2/token?"
"grant_type=authorization_code&client_id=${config.cognitoClientId}&"
"code=$hostedCode&redirect_uri=myapp://");
final response = await httpClient.post(
url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
);
if (response.statusCode != 200) {
throw HttpError.fromResponse(response);
}
final tokenData = jsonDecode(response.body) as Map<String, dynamic>;
final idToken = cognito.CognitoIdToken(
tokenData['id_token'] as String?,
);
final accessToken = cognito.CognitoAccessToken(
tokenData['access_token'] as String?,
);
final refreshToken = cognito.CognitoRefreshToken(
tokenData['refresh_token'] as String?,
);
final session = cognito.CognitoUserSession(
idToken,
accessToken,
refreshToken: refreshToken,
);
final user = cognito.CognitoUser(
null,
userPool!,
signInUserSession: session,
);
// NOTE: in order to get the email from the list of user attributes, make sure you select email in the list of
// attributes in Cognito and map it to the email field in the identity provider.
final attributes = (await user.getUserAttributes()) ?? [];
for (cognito.CognitoUserAttribute attribute in attributes) {
if (attribute.getName() == "email") {
user.username = attribute.getValue();
break;
}
}
final jwt = session.getAccessToken().getJwtToken();
if (jwt != null) {
_authCode = tokenData['access_token'] as String?;
_authToken = jwt;
}
_user = user;
}