56

Is there a way I can get a specific user account from firebase and then delete it?

For instance:

// I need a means of getting a specific auth user.
var user = firebase.auth().getUser(uid);
// Note the getUser function is not an actual function.

After, I want to delete that user and their additional data:

// This works
user.delete().then(function() {
   // User deleted.
   var ref = firebase.database().ref(
      "users/".concat(user.uid, "/")
   );
   ref.remove();
});

Firebase Documentation states that users can be deleted if they are currently logged in:

firebase.auth().currentUser.delete()

My aim is to allow logged in admin user to delete other users from the system.

2
  • Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please edit these details in or we may not be able to help.
    – Blue
    Aug 6, 2016 at 4:07
  • I rephrased the question.
    – b4oshany
    Aug 6, 2016 at 14:46

6 Answers 6

47

When using the client-side SDKs for Firebase Authentication, you can only delete the user account that is currently signed in. Anything else would be a huge security risk, as it would allow users of your app to delete each other's account.

The Admin SDKs for Firebase Authentication are designed to be used in a trusted environment, such as your development machine, a server that you control, or Cloud Functions. Because they run in a trusted environment, they can perform certain operations that the client-side SDKs can't perform, such as deleting user accounts by simply knowing their UID.

Also see:


Another common approach is to keep a allowlist/blocklist in for example the Firebase Database and authorize user based on that. See How to disable Signup in Firebase 3.x

3
  • 2
    I think FIrebase Admin SDK works only on server side and not client side, so can''t use it on ReactJS
    – Carl
    Jul 3, 2019 at 12:14
  • 2
    That is correct, and intentional. Imagine that client-side code could delete any user it wishes without authenticating first. That'd be a really bad security risk. Jul 3, 2019 at 18:51
  • In fact, It is possible to use the Admin SDK in FE, but it is not recommended as it represents a security risk for your application as you need to include the service key with the application, so, it is possible for one person to get it from your code, and them make API request with admin right to your firebase project.
    – kato2
    Nov 13, 2023 at 10:44
22

You definitely don't want to use firebase-admin in your application itself, as I think was suggested by Ali Haider, since it needs a private key which you don't want to deploy with your code.

You can however create a Cloud Function in Firebase that triggers on the deletion of a user in your Firestore or Realtime database and let that Cloud Function use firebase-admin to delete the user. In my case I have a collection of users in my Firestore with the same userid's as created by Firebase Auth, in which I save extra user data like the name and the role etc.

If you're using Firestore as me, you can do the following. If you're using Realtime database, just look up in the documentation how to use a trigger for that.

  1. Make sure your Firebase project has cloud functions initialized. There should be a folder named 'functions' in your project directory. If not: initialize Cloud Functions for your project with the following command: firebase init functions.

  2. Obtain a private key for your service account in the Firebase Console on the following page: Settings > Service accounts.

  3. Place the json-file containing the private key in the functions\src folder next to the index.ts file.

  4. Export the following function in index.ts:

export const removeUser = functions.firestore.document("/users/{uid}")
    .onDelete((snapshot, context) => {        
        const serviceAccount = require('path/to/serviceAccountKey.json');
        admin.initializeApp({
            credential: admin.credential.cert(serviceAccount),
            databaseURL: "https://<DATABASE_NAME>>.firebaseio.com"
        });
        return admin.auth().deleteUser(context.params.uid);
    });
  1. Now deploy your Cloud Function with the command firebase deploy --only functions

When a user is deleted in your Firebase Firestore, this code will run and also delete the user from Firebase Auth.

For more information on Firebase Cloud Functions, see https://firebase.google.com/docs/functions/get-started

1
  • 1
    PLEASE NOTE: Cloud Functions require that you have the Blaze plan (Pay-as-you-go) enabled Jan 20, 2022 at 13:52
14

Just apply this code same way that you have done authentication.

var user = firebase.auth().currentUser;

user.delete().then(function() {
  // User deleted.
}).catch(function(error) {
  // An error happened.
});
3
4

Using the Javascript API (not the admin SDK)

Like this answer points out for user sign in, a second app must be created to be able to delete another user than the one logged in.

This is how I did it:

  async deleteUser (user) {
    // Need to create a second app to delete another user in Firebase auth list than the logged in one.
    // https://stackoverflow.com/a/38013551/2012407
    const secondaryApp = firebase.initializeApp(config, 'Secondary')

    if (!user.email || !user.password) {
      return console.warn('Missing email or password to delete the user.')
    }

    await secondaryApp.auth().signInWithEmailAndPassword(user.email, user.password)
      .then(() => {
        const userInFirebaseAuth = secondaryApp.auth().currentUser
        userInFirebaseAuth.delete() // Delete the user in Firebase auth list (has to be logged in).
        secondaryApp.auth().signOut()
        secondaryApp.delete()

        // Then you can delete the user from the users collection if you have one.
      })
  }
2
  • If you're storing my password as plain text, I don't want to be in your application. I think this is a bad suggestion. Aug 27, 2021 at 9:00
  • 1
    @MichajaBroertjes Who says that's what I do? Nothing in this code says that. And the function secondaryApp.auth().signInWithEmailAndPassword(user.email, user.password) is built-in Firebase and takes the password that the users inputs. the user parameter is is the object containing email & password that the user just inputed. The app is built with Vue.
    – antoni
    Aug 29, 2021 at 21:43
-1

Here is the simple solution for Firebase 9+, if you want to delete the current user:

import { getAuth, deleteUser } from "firebase/auth";

const auth = getAuth();
const user = auth.currentUser;

deleteUser(user).then(() => {
  // User deleted.
}).catch((error) => {
  // An error ocurred
  // ...
});
-5

In my opinion, you can delete specific user without Firebase Admin SDK. You must to storage Username, Password of accounts you want to manage. And login with account - you declare a admin account. After that just follow steps: using firebase auth to logout -> using firebase auth to login with account you want to delete -> using firebase auth to delete that account -> using firebase auth to logout -> login again with that "admin account". Hope this solution help you to delete accounts without using Firebase Admin SDK

Not the answer you're looking for? Browse other questions tagged or ask your own question.