Search code examples
javascriptangularfirebasefirebase-authenticationgoogle-cloud-functions

Event triggered when changing a user Firebase Authentication


Detect events from a user Firebase Authentication

In my application developed in Angular along with Node.js and Firebase I need to detect events occurring in users. As inclusion, change and exclusion.

Is there a way to detect when a user is deleted, changed, or inserted through a function created in Cloud Functions?

I know that you can detect database events with a function created in Cloud Functions. I would like to detect when a user is changed, deleted or entered when the operation is done through Firebase Console > Project > Authentication.

Something in that sense:

exports.userChanged = functions.user
  .onCreate((snapshot, context) => {})

OnDelete()
OnCreate()
OnChange()

What is the best way to do this?


Solution

  • There is onCreate and onDelete, you can read it from the docs.

    For the update case, you should rely on the RTD. Actually, you could rely completely on the RTD.

    //Create a user on the rtd
    functions.auth.user().onCreate((user) => {
        return usersRef.child(user.uid).set(user);
    });
    
    //Update the user by listening to a change on the RTD
    functions.database.ref('/users/{uid}')
        .onWrite((change, context) => {
             //If you needed it you can update the user
             admin.auth().updateUser(uid, {
             });
    
             //if some condition, then delete it
             admin.auth().deleteUser(uid)
    
             //do more
        }); 
    

    Using the update user option you can even disable the account, take a look at this other answer

    You can use the admin sdk inside of Functions directly, this is the doc