Search code examples
firebasegoogle-cloud-firestorefirebase-authenticationgoogle-cloud-functionsfirebase-security

Firebase Session differentiation inside a function


I have a single user USER_X. USER_X authenticates into my FireBase app, and then USER_X authenticates into my app a second time from a different location/device. They both authenticate using username/password.

If I'm inside a firebase function, how do I compare the second session with the first login and know that these are different devices/sessions?

I thought about accessing the token, but those appear to be short-lived and if they are short-lived then it could be the same session just an hour apart.

I'm looking for something that I can access from a Firebase functions and firestore rules.


Solution

  • The DecodedToken has a auth_time property which is time in seconds since the Unix epoch, when the end-user authentication occurred. This can be used to differentiate between sessions unless user logs in on multiple devices at the same time.

    This value is not set when this particular ID token was created, but when the user initially logged in to this session. In a single session, the Firebase SDKs will refresh a user's ID tokens every hour. Each ID token will have a different iat value, but the same auth_time value.

    Although this can be accessed only in callable functions (which are triggered by user actions) and not background functions such as Firestore triggers as background functions are not triggered by any user.

    Other option would be storing the timestamp when they logged in local storage and reading it whenever necessary.