Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Amplify 2.15.2 when i first install the App it says user already signed in #3242

Closed
jav8r1at opened this issue Sep 27, 2023 · 5 comments
Closed
Assignees
Labels
auth Issues related to the Auth category

Comments

@jav8r1at
Copy link

Describe the bug

Im working in siwft when i first install the App and login with amplify version Amplify 2.15.2 it says user already signed in . Im not sure why this is happening could you please tell.

Steps To Reproduce

Im working in siwft when i first install the App and login with amplify version Amplify 2.15.2 it says user already signed in . Im not sure why this is happening could you please tell.

Expected behavior

its should login even if i would have previously logged in in a different device

Amplify Framework Version

2.15.2

Amplify Categories

Auth

Dependency manager

Swift PM

Swift version

5.5

CLI version

2.15.2

Xcode version

14.2

Relevant log output

No response

Is this a regression?

Yes

Regression additional context

No response

Platforms

No response

OS Version

16+

Device

iPHONE 16

Specific to simulators

No response

Additional context

No response

@harsh62 harsh62 self-assigned this Sep 27, 2023
@harsh62 harsh62 added the auth Issues related to the Auth category label Sep 27, 2023
@harsh62
Copy link
Member

harsh62 commented Sep 27, 2023

@jav8r1at

Would you be able to share the code example that you are trying and also verbose logs which can help us determine whats going on.

You can enable verbose logging to the console by doing this before calling Amplify.configure:

Amplify.Logging.logLevel = .verbose

Also would you be able to share if any app that uses amplify was ever installed on the device you are testing.

@jav8r1at
Copy link
Author

No it was installed the very first time and i encountered the issue. After the second time this didnt happen

@jav8r1at
Copy link
Author

jav8r1at commented Sep 28, 2023

here is the code sample

func userLogin(userId: String, password: String?,completion: @escaping (Bool?, String?, Error?) -> Void) async {
        do {
            let signInResult = try await Amplify.Auth.signIn(username: userId, password: password)
            switch signInResult.nextStep {
            case .confirmSignInWithSMSMFACode(let deliveryDetails, let info):
                print("SMS code send to \(deliveryDetails.destination)")
                print("Additional info \(String(describing: info))")
                
                // Prompt the user to enter the SMSMFA code they received
                // Then invoke `confirmSignIn` api with the code
                
            case .confirmSignInWithCustomChallenge(let info):
                print("Custom challenge, additional info \(String(describing: info))")
                
                // Prompt the user to enter custom challenge answer
                // Then invoke `confirmSignIn` api with the answer
                
            case .confirmSignInWithNewPassword(let info):
                print("New password additional info \(String(describing: info))")
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: NSNotification.showResetPasswordViewForFirstLogin,
                                                    object: nil, userInfo: [:])
                }
                
                // Prompt the user to enter a new password
                // Then invoke `confirmSignIn` api with new password
                
            case .resetPassword(let info):
                print("Reset password additional info \(String(describing: info))")
                
                // User needs to reset their password.
                // Invoke `resetPassword` api to start the reset password
                // flow, and once reset password flow completes, invoke
                // `signIn` api to trigger signin flow again.
                
            case .confirmSignUp(let info):
                print("Confirm signup additional info \(String(describing: info))")
                
                // User was not confirmed during the signup process.
                // Invoke `confirmSignUp` api to confirm the user if
                // they have the confirmation code. If they do not have the
                // confirmation code, invoke `resendSignUpCode` to send the
                // code again.
                // After the user is confirmed, invoke the `signIn` api again.
            case .done:
                do {
                    let session = try await Amplify.Auth.fetchAuthSession()
                    
                    // Get cognito user pool token
                    if let cognitoTokenProvider = session as? AuthCognitoTokensProvider {
                        let tokens = try cognitoTokenProvider.getCognitoTokens().get()
                        print( tokens.idToken)
                        print(tokens.accessToken)
                        print(tokens.refreshToken)
                        let tokenDetails = self.getApiKeyFromToken(token: tokens.idToken )
                        Task{
                            //Store User token against email id as a user id
                            DispatchQueue.main.async{
                                RealmDatabaseManager.shared.saveLoginUserDetails(userId: userId, idToken: tokens.idToken, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, tokenDetails: tokenDetails)
                            }
                        }
                        completion(true, "User has Logged In Successfully.", nil)
                        // Do something with the JWT tokens
                    }
                } catch let error as AuthError {
                    print("Fetch auth session failed with error - \(error)")
                }
                //decode the Id token
                
                // Use has successfully signed in to the app
                print("Signin complete")
            }
        } catch let error as AuthError{
            print ("Sign in failed \(error)")
            completion(false, error.errorDescription, error)
        }
        catch {
            print(error)
            completion(false,"", nil)
        }
    }
    

@jav8r1at
Copy link
Author

Another question i have is how to check if session is expired and is Amplify not smart enough to call fetchauthsession internally

@harsh62
Copy link
Member

harsh62 commented Sep 28, 2023

@jav8r1at

Your code sample is correct and should not cause any problems. Also I am not able to see code path where an already user signed in error would come up. If you see the error again, please share the verbose logs, so that I can see what is happening. Ideally if there is no user logged in before, keychain should be empty, and Amplify library will not be able to get any user details. Hence, it should never show a user as logged in when the Lib

Amplify would not automatically refresh the session in the background. But that being said, if you call any other Amplify API's, they would call fetchAuthSession under the hood to proactively refresh the session (only if the session is about to expire).

If for some reason, you want to force refresh the session, you can call fetchAuthSession with an option as follows

Amplify.Auth.fetchAuthSession(options: .forceRefresh())

@ruisebas ruisebas added the pending-community-response Issue is pending response from the issue requestor label Sep 28, 2023
@github-actions github-actions bot removed the pending-community-response Issue is pending response from the issue requestor label Oct 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auth Issues related to the Auth category
Projects
None yet
Development

No branches or pull requests

4 participants