Smitherson
Smitherson

Reputation: 433

Firebase - Automatically sign out user onDisconnect

Since I have noticed that once a user signs in with email and password, on reopening the application the session will not have expired and there is no need for a new authentication, I wish to avoid this.

I want to automatically .signOut() a user when .onDisconnect is triggered. How can I achieve this? I have tried with the following code, but unsuccessfully:

firebase.auth().onDisconnect().signOut();

Upvotes: 1

Views: 1540

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 599686

The onDisconnect() is related to the database connection, and has little to do with your authenticated user. As in: onDisconnect() may fire when your user is signed in, simply because the connection to the database drops temporarily.

But more importantly: onDisconnect handlers run server-side, once the server detects that the client has disappeared. When this is because if a dirty disconnect (e.g. the app crashes), there is no way for the client to detect this anymore.

The most likely approach you'll want is to simply sign the user out when they close the app.

Alternative you might want to attach a listener to .info/connected in your client. This is a client-side listener that fires when the client detects that it is connected or disconnected.

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317740

When you say "onDisconnect", I'm assuming that you mean Realtime Database onDisconnect triggers.

The first thing to know about onDisconnect is that it triggers when the socket connection between Realtime Database and the client app is closed. This could happen for any number of reasons, and it can happen at any time, even if the app seemingly has a good internet connection. So, be careful about what you're trying to do here.

Also, onDisconnect triggers can only affect data in the database directly, and nothing else. So, this limits what you can effectively accomplish. You can't perform any action in the client app in response on an onDisconnect.

Between these two facts, what you're trying to do isn't really possible, and, I don't think it's desirable. You could end up logging out the user just because their train went underground momentarily, or if they simply switched out of the application for some time. This would be massively inconvenient to the user.

If you want to automatically log out the user, I strongly suggesting finding some other way to do this, such as writing some code to remember how long it's been since the user used your app, and forcing the logout on the on the client app based on your preferred logic.

Upvotes: 3

Related Questions