Abu Saeed
Abu Saeed

Reputation: 1170

How to prevent user from reading after password change?

In my firebase realtime database, only authenticated user can read data. Suppose a user(suppose xyz) is logged in in app and I reset his password. After resetting/changing password, xyz is still able to read/write in database until I reauthenticate and logged him out manually(through code). The problem is, if someone modify app source code and remove manually log-out part, how do I prevent that user from reading/writing to database?

Upvotes: 0

Views: 174

Answers (2)

DIGI Byte
DIGI Byte

Reputation: 4163

You can do this by invoking a cloud function with the new password, I would advise encoding the password and decoding it but this is out of the scope of this question.

// declare function
exports.updatePass= functions.https.onCall((data, context) => {
return admin
  .auth()
  .updateUser(context.auth.uid, { password: 'newPassword' })
  .then(async (userRecord) => {
    const utcRevocationTimeSecs = await new Date(userRecord.tokensValidAfterTime).getTime() / 1000;
    return admin.database().ref('metadata/' + uid)
    .set({ revokeTime: utcRevocationTimeSecs })})
  .then(() => admin.auth().revokeRefreshTokens(context.auth.uid))
  .then(() => return {message: "success"};
  .catch((error) => {
    return error;
  });
});

This will write the changes to the realtime database of which you can listen to changes, and use within your Security Rules, This can easily swap this out for firestore if needed.

{
  "rules": {
    "metadata": {
      "$user_id": {
        // this could be false as it is only accessed from backend or rules.
        ".read": "$user_id === auth.uid",
        ".write": "false",
      }
    }
  }
}

Source:

Upvotes: 2

Frank van Puffelen
Frank van Puffelen

Reputation: 599651

Firebase Authentication is based on tokens, the shorted lived (ID token) of which is valid for an hour. Changing the password on the account does not invalidate existing ID token(s), so if you want the user to lose access immediately, you'll have to do that in another way.

A common way is to keep a banlist/blocklist in the database, for the UIDs that are supposed to be blocked even if they have a valid ID token. This scenario is described more fully in the documentation on detecting ID token revocation.

With this approach though, you don't have a clear trigger on when to unblock/reenable the user's access, as there is no callback when their password changes. The best I can think of is to periodically run a Cloud Function to check if the user's password hash has changed, but I'm hoping somebody comes up with a better option for this step.

Upvotes: 1

Related Questions