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.
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:
delete firebase authenticated user from web application
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
I know this is an old question, but I found another solution to this.
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.
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.
Obtain a private key for your service account in the Firebase Console on the following page: Settings > Service accounts.
Place the json-file containing the private key in the functions\src folder next to the index.ts file.
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);
});
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
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.
});
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.
})
}
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
Related
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.
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:
delete firebase authenticated user from web application
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
I know this is an old question, but I found another solution to this.
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.
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.
Obtain a private key for your service account in the Firebase Console on the following page: Settings > Service accounts.
Place the json-file containing the private key in the functions\src folder next to the index.ts file.
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);
});
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
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.
});
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.
})
}
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
I want to use Firebase Storage (web version 9.6.0) but the access to Firebase Storage is being denied with the following error:
unhandledRejection: FirebaseError: Firebase Storage: User is not authenticated, please authenticate using Firebase Authentication and try again. (storage/unauthenticated)
You would want to say to me that I just need the user to be authenticated, but two problems:
the user is already authenticated (getAuth().currentUser returns something)
the rules in Firebase Storage don't say that a user needs to be authenticated:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
}
}
The problem is caused when I try this:
// initializeApp(config) etc.
const storage = getStorage() // enabled in Firebase console
const a_correct_path = "something..."
const reference = ref(storage, a_correct_path) // this is working (I get the right reference)
const url = getDownloadURL(reference) // this throws the error
NOTE: Because I have already had problems with it, please not that I'm using App Check which I have enforced for the Storage feature.
Why did I do wrong?
Firstly,
The
const a_correct_path = ""
Can't be empty and should have the correct path if it's in a folder.
But if that doesn't help... Reset your storage rules to the first one.
If that doesn't work, check the line where you imported things from firebase
On the Firebase Console, go to Authentication. Check that the user that you are logged in with appears there. If the user is not there then that means you are not authenticating users with Firebase Authentication, and maybe you're just adding users to your Firestore. That is why the error is placing emphasis on Firebase Authentication.
User is not authenticated, please authenticate using Firebase Authentication and try again.
How I can to cleanup user data from Cloud Firestore after a user sign out
I want to remove everything related to the user (collections, sub-collections, and images) a user sign out.
I use frigger a function on user deletion in Cloud Function
exports.cleanupUserData = functions.auth.user().onDelete((user) => {
return ...
});
Are there any alternatives to solve this problem?
There are no Cloud Functions triggers for when a user signs in or out. There are currently just triggers for when a user account is created or deleted. With Firebase Authentication, users are expected to be able to sign in and out repeatedly without disruption to their data.
I think that you can clone your user in Firebase Authentication to Realtime Database or Firestore and use the data in it. After that, to deal with your question is make a logic in SignOut function to clear all data in Realtime Database or Firestore based on your choice.
For a work-related app I use Firebase authentication with Microsoft. In this case, however, it is important that only people from my company (we use Office 365) can sign into this application. I have everything set-up and working in a non-firebase context. But when I use Firebase for authentication, it seems to always point to the /common/ endpoint. This causes problem with my single-tenant-application. If I set the application to accept all tenants, the app works again. But obviously, now everyone can log into my application.
The pop-up is called with a rather conventional:
const provider = new auth.OAuthProvider("microsoft.com");
provider.setCustomParameters({
tenant: "[tenantName].com"
});
auth()
.signInWithPopup(provider)
.then(result => {
But I can't find any instructions on changing the oauth endpoint to use the single tenant endpoint.
How would I go about doing this?
But I can't find any instructions on changing the oauth endpoint to
use the single tenant endpoint.
We can not change the oauth endpoint, even though we add the tenant information to customParameters. The endpoint always use common as the value of tenant. This is the default design.
If we enable Microsoft as a sign-in provider, users using Microsoft accounts (Azure Active Directory and personal Microsoft accounts) can sign in.
Turns out the above is not exactly true. I've switched to signing in with a redirect, and now it (mysteriously) works.
const provider = new auth.OAuthProvider("microsoft.com");
provider.setCustomParameters({
tenant: "[tenant].com"
});
auth().signInWithRedirect(provider);
I have tested this. The tenant is named in the redirect, and people from other tenants cannot log in.
I used mongoose database before. After the testing process and all we can delete the data from the mongoose website manually. Even the collection.
Now I am using firebase as my database and my question is that is there any functionality like removing authenticated user data manually from the database just like we do in mongoose. Or do we need to code to remove a particular user data from firebase?
I have a firebase.js
import * as firebase from 'firebase';
const config = {
apiKey: "someKey",
authDomain: "some domain",
databaseURL: "someURL",
projectId: "someID",
storageBucket: "someBucket",
messagingSenderId: "SomeId"
};
const firebaseApp = firebase.initializeApp(config);
export default firebaseApp;
and an index.js file:
import firebaseApp from './firebase';
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
console.log(user);
} else {
console.log('user needs to be signed in');
}
})
On submission I am seeing user in the web console
Is there any way to visualize the authenticated user in the firebase console, so that I can delete it from the firebase web console?
in mongodb there will be a collection for the authentication purposes. That contain,say the username and password. Which is a collection of its own. And other collections based on other datas. What I am asking is that the user data authenticated by the above process, needs to be stored somewhere right in the firebase. Is there any way to get that user data and delete it?
The Firebase Console is your backend entry-point to your app's data, features and services.
The Database section of the console enables you to freely add & remove data in the Realtime Database and Cloud Firestore:
Realtime Database
Cloud Firestore
There is a separate section for Authentication in the Firebase Console. When a user registers for your app, their profile data is passed to Firebase from the authentication provider (Google, Facebook, etc), but only the identifier (username, email, phone number), created date, signed in date and unique ID are displayed in the Firebase Console:
You can manually delete user accounts from the Firebase Console without having to write code to do so. Deleting an account will delete the associated authentication data and will stop the user from logging into your app.
To manually delete a user account:
Login to Firebase Console from a desktop browser
Select Authentication from the left menu
Hover over a user account in the list
Click the 3-dot icon on the right of the user row
Click "delete account" from the context menu