user6934210
user6934210

Reputation:

How would I be able to detect if the user still has an auth session in firebase?

I was able to find this: How to check if user has valid Auth Session Firebase iOS?, but it wasn't able to answer my question.

What I'm trying to do: I know this will never happen unless the user deletes their own account, but would I know if the user still has an auth session?

For example, under the authentication tab, I deleted the entry that was created by the test user and even though I use these pieces of code:

in AppDelegate.swift:

if Auth.auth().currentUser == nil {
        try! Auth.auth().signOut()
}

and in my main view controller:

private func checkIfSignedIn() {
    Auth.auth().addStateDidChangeListener { (auth, user) in
        if user != nil {
            // code to stay signed in
        } else {
            // code for dismissing the controller and moving to login controller
        }
    }
}

When I run erase the entry from the Authentication section of firebase console and re-run the app, the user is still logged in and still has a valid UID (I was able to print it to check).

The only time it detects when it should sign out and doesn't sign back in again is when I manually click the sign out button. Is there a way to work around this?

Upvotes: 1

Views: 1775

Answers (3)

Sti
Sti

Reputation: 8494

What were you trying to do with the code in your AppDelegate? Surely, if currentUser is nil, then you're already signed out, meaning that this code would never do anything?

If this is for testing-purposes, and you simply want to test the listener, then you need to be signed-in before signing out, I.E change it to if Auth.auth().currentUser != nil in AppDelegate.

Upvotes: 0

Simon Cadieux
Simon Cadieux

Reputation: 347

Look at this: https://firebase.google.com/docs/auth/ios/manage-users#re-authenticate_a_user

I am not an IOS Dev but from what i read from the doc, it might look like there something missing in your code and it looks really familiar to what in the Stackoverflow answer pointed out by WillB at: How can I detect if the user was deleted from Firebase auth?

Upvotes: 1

Sankha Karunasekara
Sankha Karunasekara

Reputation: 1726

You're not calling StateDidChangeListener. Instead you're telling Firebase to call you when the authentication state changes, which may happen a few times when the page is being re-loaded.

When a page is getting loaded and there was previously a user signed in, the auth state may change a few times, while the client is figuring out if the user's authentication state it still valid. Auth.auth().currentUser will always return a valid user if you already signed in. so use it.

private func checkIfSignedIn() {
   if Auth.auth().currentUser != nil {
      // code to stay signed in
   }else{
      // redirect to sign in page
   }
}

Hope it helps.

Upvotes: 1

Related Questions