Home > Net >  AWS Amplify for Flutter: User is signed in but cannot get current user
AWS Amplify for Flutter: User is signed in but cannot get current user

Time:11-07

I am having a weird issue while introducing AWS Amplify to my flutter project.

I have the following code. When I try to sign in a user. I get InvalidStateException(message: There is already a user which is signed in. Please log out the user before calling showSignIn., recoverySuggestion: Operation performed is not a valid operation for the current auth state, underlyingException: null) in the AuthException (at the end of the signIn function, line 70 in the image).

However, when I try to get current user, the exception shows that I already signed out.

enter image description here

Feel like it's conflict. Can anyone please help on it? Thank you

signIn(String password, void Function(String, String) onSuccess,
      Future<void> Function(String) onFailure) async {
    AuthUser? currentUser;

    try {
      currentUser = await Amplify.Auth.getCurrentUser();
      if (currentUser.username == _username) {
        _isSignIn = true;
      } else {
        await Amplify.Auth.signOut();
        _isSignIn = false;
      }
    } on Exception catch (e) {
      _isSignIn = false;
    }

    try {
      SignInResult res;
      if (!_isSignIn) {
        res = await Amplify.Auth.signIn(
          username: _username,
          password: password,
        );
        if (res.isSignedIn) {
          _isSignIn = res.isSignedIn;
          currentUser = await Amplify.Auth.getCurrentUser();
        }
      }

      if (_isSignIn && currentUser != null) {
        List<AuthUserAttribute> attributes =
            await Amplify.Auth.fetchUserAttributes();

        onSuccess(
            currentUser.userId,
            attributes
                .firstWhere(
                    (attribute) => attribute.userAttributeKey == 'email')
                .value);

        _isEmailVerified = attributes
                .firstWhere((attribute) =>
                    attribute.userAttributeKey == 'email_verified')
                .value ==
            'true';
      }
    } on NotAuthorizedException catch (notAuthorizedException) {
      await onFailure(notAuthorizedException.message);
    } on AuthException catch (e) {
      print(e);
      final a = await Amplify.Auth.getCurrentUser();

      await onFailure(e.message);
    }
  }

CodePudding user response:

Try to call signOut() before every signIn(), in this way you will make sure to avoid conflicts:

void signIn() async {
  try {
    await Amplify.Auth.signOut();
  } on AuthException catch (e) {
  }
    SignInResult res = await Amplify.Auth.signIn(
        username: userNameController.text.trim(),
        password: passwordController.text.trim());
    if (res.isSignedIn) {
     _isSignIn = res.isSignedIn;
     currentUser = await Amplify.Auth.getCurrentUser();
    }
 
}
  • Related