4

The database structure looks like this

-LGw89Lx5CA9mOe1fSRQ {
    uid: "FzobH6xDhHhtjbfqxlHR5nTobL62"
    image: "https://pbs.twimg.com/profile_images/8950378298..."
    location: "Lorem ipsum, lorem ipsum"
    name: "Lorem ipsum"
    provider: "twitter.com"
}

How can I delete everything, including the -LGw89Lx5CA9mOe1fSRQ key programmatically?

I looked at this, but it's outdated and deprecated Firebase: removeUser() but need to remove data stored under that uid

I've also looked at this, but this requires for user to constantly sign in (I'm saving the user ID in localStorage) and it returns null on refresh if I write firebase.auth().currentUser. Data records and user accounts are created through social network providers and I can see the data both on Authentication and Database tab in the Firebase console.

I've tried with these piece of code but it does nothing.

 // currentUser has a value of UID from Firebase
 // The value is stored in localStorage
 databaseChild.child(currentUser).remove()
   .then(res => {
       // res returns 'undefined'
       console.log('Deleted', res);
   })
   .catch(err => console.error(err));

The bottom line is, I need to delete the user (with a specific UID) from the Authentication tab and from the Database at the same time with one click.

I know that there is a Firebase Admin SDK but I'm creating a Single Page Application and I don't have any back end code. Everything is being done on the front end.

Any kind of help is appreciated.

Vladimir Jovanović
  • 5,143
  • 5
  • 21
  • 42
  • try `var database = firebase.database(); var del=database.ref().child("-LGw89Lx5CA9mOe1fSRQ").remove();` – Peter Haddad Jul 09 '18 at 13:39
  • That won't work since the `-LGw89Lx5CA9mOe1fSRQ` is generated by the Firebase upon writing the data in the database, but your code is the same as the one that I tried, presented in this question, under the `I've tried with this piece of code but it does nothing.` – Vladimir Jovanović Jul 09 '18 at 13:42
  • What id are u using in your code? – Peter Haddad Jul 09 '18 at 13:45
  • The one that is generated in the **Authentication** tab, under the **User UID**. But I'll try to perform this action with Cloud Functions like the @JeremyW suggested. – Vladimir Jovanović Jul 09 '18 at 13:47

2 Answers2

6

With suggestions from @jeremyw and @peter-haddad I was able to get exactly what I want. Here is the code that is hosted on Firebase Cloud Functions

const functions = require('firebase-functions'),
    admin = require('firebase-admin');

admin.initializeApp();

exports.deleteUser = functions.https.onRequest((request, response) => {
    const data = JSON.parse(request.body),
        user = data.uid;

    // Delete user record from Authentication
    admin.auth().deleteUser(user)
        .then(() => {
            console.log('User Authentication record deleted');
            return;
        })
        .catch(() => console.error('Error while trying to delete the user', err));

    // Delete user record from Real Time Database
    admin.database().ref().child('people').orderByChild('uid').equalTo(user).once('value', snap => {
        let userData = snap.val();
        for (let key of Object.keys(userData)) {
            admin.database().ref().child('people').child(key).remove();
        }
    });

    response.send(200);
});

Also, if you are facing CORS errors, add the mode: 'no-cors' option to your fetch() function and it will work without any problems.

Vladimir Jovanović
  • 5,143
  • 5
  • 21
  • 42
3

The link you already found for deleting the user-login-account client-side is your only option if you want to keep the action on the client. Usually you want to keep most of the actions for things like account creation/deletion on the server for security reasons, and Firebase forces the issue. You can only delete your account if you were recently logged in, you can't have client-side start deleting old/random accounts.

The better option is to create your own Cloud Function to handle everything related to deleting a user. You would have to use the Admin SDK that you already found for this... but you could have that Cloud Function perform as many actions as you want - it will have to delete the user from the Auth tab, and delete the matching data in the Database.

JeremyW
  • 5,157
  • 6
  • 29
  • 30
  • that will only delete the user from the authentication console and not from the database – Peter Haddad Jul 09 '18 at 13:48
  • Right, there is no single command to delete from the Auth tab AND the database tab - Firebase has no way of knowing what your database structure is like. You'd need to code your Cloud Function to make that call to the Auth portion to delete the user from there, AND use the admin SDK to make ANOTHER call to the database to delete their details there. – JeremyW Jul 09 '18 at 13:54
  • The benefit of doing it via the admin SDK inside a Cloud Function is that you avoid the issue of the client side limitation `To delete a user, the user must have signed in recently.`.... and that this way the client side makes a single call - the single call to the Cloud Function - and then the cloud function can handle everything. (everything = delete from auth tab, delete from database tab, anything else you want to happen on user delete, etc...) – JeremyW Jul 09 '18 at 13:57
  • 1
    Thank you again. I've worked with serverless code before, on Webtask.io, it shouldn't be a problem. Thanks again, both of you. – Vladimir Jovanović Jul 09 '18 at 14:50