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
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
Here is an issue I am having with Firebase and push notifications.
In a web app, I want a button which sends a remote notification when clicked. This notification is meant to be received by an iOS app working together with my web-app.
The present question is about how to make this work. The web offers some example of how to receive notifications in a web application, but I did not find much about sending one, and this is precisely what I need to do.
Below is the relevant code, the problem is to know how to write the code for the SendNotific() function, and maybe some other details. I hope someone, expert on the subject will be able to provide me with some advice.
<body>
<script>
// Initialize Firebase.
var config = {
apiKey: "myyKeyyy",
authDomain: "......firebaseapp.com",
databaseURL: "https://......firebaseio.com",
projectId: "....",
storageBucket: "........appspot.com",
messagingSenderId: "........."
},
app = firebase.initializeApp(config);
db = firebase.firestore(app);
const messaging = firebase.messaging();
function SendNotific() {
// Code to send a notification.
........
}
</script>
<input type='button' id='PushNotif' style='font-size:20px' value='Send notification!' onClick='SendNotific()'>
</body>
You cannot send notifications using client, for sending notifications firebase has an Admin SDK which should be used by the application server. Though if you are up to building a serverless app then you should consider Firebase Cloud functions which you can trigger using a HTTP endpoint and the cloud function can handle the notifications sending job.
I am not sure where to begin but I recently saw 'Firebase' while searching for no server database, while it seems interesting to me, I was little worried about putting my api codes directly in the js files, which obviously can be seen through source but I have read that you can change the read/write rules and need authentication. so I no longer worried about API after reading through some pages
but the main question is:
I wanted to create an admin portal for my page, so example my admin page is located in localhost/admin/ <<< The page will simply have a login form which is to access the portal, so everything is set
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
window.location = '/portal.html'
}
else {
// Do nothing
}
});
$("#loginbtn").click(function() {
var email = $('#login-name').val();
var password = $('#login-pass').val();
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(function(error) {
// Handle Errors here.
});
});
So when I log in successfully it will redirect me to that page but can someone just look through source code and then go that page manually and enter it?
Or even if I intend to build one page application and decide to change the page state after login, whatever functions i'm going to do after that, can someone still find out and inject the code ?
I'm not really expert on this but this what I was thinking before starting my project, so is there is any other way around?
If you want to add admin capabilities and you are using Firebase real-time database, you need to set some custom Firebase rules to only allow admins to access restricted data. So if a non-admin user signs in, they are unable to modify/access admin only data.
One way to do this with Firebase rules is to have a /whitelist node with uid1: "bojeil#bla.com", uid2: "puf#bla.com" for storing all whitelisted admin UIDs and then a top-level security rule for restricted admin only nodes like ".write": "auth != null && root.child('whitelist').child(auth.uid).exists()". It's fairly simple, but goes a long way.
If you are not using real-time database and building a traditional web application, you need to protect restricted admin only resources. You will need to send the Firebase ID token to your backend. You can do that by setting a session cookie with its value and making sure to update that session cookie every hour or so when the Firebase ID token is refreshed. When the cookie is sent with your request, you check for it, decode it (you can use the Firebase Admin SDKs for that) and check that the user it belongs to is an admin. If so, you can allow access, otherwise you block access. On every page, you would add an onAuthStateChanged listener. If that triggers with null, you redirect to the sign-in page. If the session cookie contains an ID token for a non-admin, you can do a HTTP redirect on your server to the user non-admin section.
tldr; you need to enforce the check on your backend by sending the Firebase ID token with the request and double checking its user has adequate privileges.
I am new to angular 2 and I have successfully implemented Firebase authentication which is based on email and password the user sets.
Once the user log in, the Firebase variable is initialized and can be accessed throughout the app however once the user is in the app and refreshes the page the Firebase variable becomes null.
My question is how can I maintain the Firebase state after refresh occurs. Tried the local storage approach but that seems to be not suitable. most of the relevant queries in SO are for AngularJS.
Any ideas?
Edit
Firebase is initialized in appcomponant.ts file
firebase.initializeApp({
apiKey: 'A******E',
authDomain: 'e******m',
databaseURL: 'h*****m',
projectId: 'e******r',
storageBucket: 'e******m',
messagingSenderId: '****93***'
});
In my login service I am using
signInUser(email: string, password: string) {
return firebase.auth().signInWithEmailAndPassword(email, password);
}
Once the user authenticated he is directed to a page called settings. In the settings component I would like to get the email of the authenticated user. this all goes well when the flow is userlogin-->settings page, firebase is not null.
Issue starts when the user is in the settings page a hit F5 to refresh the page, at that point Firebase object becomes null.
User LocalStorage to store the token you receive back from firebase. To set in local storage you can do
localStorage.setItem('fireBaseToken', 'token');
then in your main app.component.ts check if the token exists if it does add it to your variable otherwise redirect user to login again.
NOTE
The Angular CLI by default should add "dom" to your tsconfig.json otherwise add it your self.
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