I am currently using Msal react library for Azure authentication.I am currently in the situation of 2 accounts signed in but my code picks up the first one in accounts array which is accounts[0].
How to get the account selected here?
When signing in the user you can set the active account:
const { instance } = useMsal();
instance.loginPopup().then((response) => {
// After a successful login set the active account to be the user that just logged in
instance.setActiveAccount(response.account);
});
now you can retrieve the active account using:
instance.getActiveAccount()
I have to show data belonging to a user that logged in.
My database structure is as follows:
Users/Drivers/Uid/name,phone...
How can I show the data of a user that logged in by using JavaScript?
If you have a structure like that, you can display all data for the currently logged in user with:
var currentUser = firebase.auth().currentUser;
var userRef = firebase.database().ref("Users/Drivers").child(currentUser.uid);
userRef.on("value").then(function(snapshot) {
console.log(snapshot.val());
})
I apologize if the title is not worded properly. I am seeking advice on the recommended way to perform the following operation on Firebase.
I am using Firebase for a group collaboration kind of app (think of Whatsapp). A user registers using his phone number and is added as a user to the Firebase database. A user is stored as follows on Firebase
users
-KGvMIPwul2dUYABCDEF
countryCode: 1
id: -KGvMIPwul2dUYABCDEF
mobileNumber: 1231231234
name: Varun Gupta
Whenever a user opens the app, I want to check who all in user's phone contact list is also using my app and present those contacts in the app. The phone number is used to check if a person in the phone contacts is using the app. To achieve this, I store the user contacts list to Firebase which triggers a Firebase function to compute the contacts also using my app and store them separately on Firebase.
To figure out who is using my app, I create a map of all the users in Firebase keyed on the phone number and a combination of country code and phone number. The value is the user ID which would be -KGvMIPwul2dUYABCDEF for the above example. So, the map would have the following two entries for the user
{
1231231234: -KGvMIPwul2dUYABCDEF
11231231234: -KGvMIPwul2dUYABCDEF
}
I create the above for all the users and then I just query for each contact, if there is an entry for the user's phone number in the map and figure out the list of users who are using the app.
Below are the excerpts from the code. Right now it is done in a firebase-queue worker but I intend to move it to a Firebase function
// This piece of code is used to read the users in Firebase and create a map as described above
ref.child('users').on('child_added', (snapshot) => {
var uid = snapshot.key;
var userData = snapshot.val();
// Match against both mobileNumber and the combination of countryCode and mobileNumber
// Sanity check
if(userData.mobileNumber && userData.countryCode) {
contactsMap.set(sanitizePhoneNumber(userData.mobileNumber), uid);
contactsMap.set(sanitizePhoneNumber(userData.countryCode + userData.mobileNumber), uid);
}
});
// This piece of code is used to figure out which contacts are using the app
contactsData.forEach((contact) => {
contact.phoneNumbers.forEach((phoneNumber) => {
var contactsMapEntry = contactsMap.get(sanitizePhoneNumber(phoneNumber))
// Don't add user himself to the contacts if he is present in the contacts
if(contactsMapEntry && contactsMapEntry !== uid && !contactsObj[contactsMapEntry]) {
const contactObj = {
name: createContactName(contact),
mobileNumber: phoneNumber.number,
id: contactsMapEntry
}
contactsObj[contactsMapEntry] = contactObj
currentContacts.push(contactObj)
}
});
});
// After figuring out the currentContacts, I do some processing and they are pushed to Firebase which are then synched with the app
My concern is that as the number of users increases, this will start to become slow because I am reading all the users from the Firebase creating this map in memory for every request to figure out the contacts who are using the app or would I be okay with this brute force kind of method and shouldn't worry too much.
Should I consider duplicating data like below also
contacts
1231231234: -KGvMIPwul2dUYABCDEF
11231231234: -KGvMIPwul2dUYABCDEF
and then just query for /contacts/{contact phone number}
If there is an even better method to achieve this workflow, please suggest.
I am looking to fetch Auth User(s) UID from Firebase via NodeJS or Javascript API.
I have attached screenshot for it so that you will have idea what I am looking for.
Hope, you guys help me out with this.
Auth data is asynchronous in Firebase 3. So you need to wait for the event and then you have access to the current logged in user's UID. You won't be able to get the others. It will get called when the app opens too.
You can also render your app only once receiving the event if you prefer, to avoid extra logic in there to determine if the event has fired yet.
You could also trigger route changes from here based on the presence of user, this combined with a check before loading a route is a solid way to ensure only the right people are viewing publicOnly or privateOnly pages.
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User logged in already or has just logged in.
console.log(user.uid);
} else {
// User not logged in or has just logged out.
}
});
Within your app you can either save this user object, or get the current user at any time with firebase.auth().currentUser.
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged
if a user is logged in then the console.log will print out:
if (firebase.auth().currentUser !== null)
console.log("user id: " + firebase.auth().currentUser.uid);
on server side you can use firebase admin sdk to get all user information :
const admin = require('firebase-admin')
var serviceAccount = require("./serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://yourprojecturl.firebaseio.com",
});
admin.auth().listUsers().then(data=>{
console.log(data.users)
})
This is an old question but I believe the accepted answer provides a correct answer to a different question; and although the answer from Dipanjan Panja seems to answer the original question, the original poster clarified later in a reply with a different question:
Basically, I need to generate token from UID by Firebase.auth().createCustomToken(UID) to sign in user on firebase with the following function firebase.auth().signInWithCustomToken(token).
Because the original question was clarified that the intent is to use
createCustomToken and signInWithCustomToken, I believe this is a question about using the Firebase Admin SDK or Firebase Functions (both server-side) to provide custom authentication, probably based on a username and password combination, rather than using an email address and password.
I also think there's some confusion over "uid" here, where in the code example below, it does NOT refer to the user's Firebase uid, but rather the uid indicated in the doc for createCustomToken, which shows:
admin
.auth()
.createCustomToken(uid)
.then((customToken) => {
...
In this case, the uid parameter on the createCustomToken call is not the Firebase uid field (which would not yet be known), thus providing a series of frustrating replies to the coder asking this question.
Instead, the uid here refers to any arbitrary basis for logging in for which this custom auth will support. (For example, it could also be an email address, social security number, employee number, anything...)
If you look above that short code block from the documentation page, you'll see that in this case uid was defined as:
const uid = 'some-uid';
Again, this could represent anything that the custom auth wanted it to be, but in this case, let's assume it's username/userid to be paired with a password. So it could have a value of 'admin' or 'appurist' or '123456' or something else.
Answer: So in this case, this particular uid (misnamed) is probably coming from user input, on a login form, which is why it is available at (before) login time. If you know who is trying to log in, some Admin SDK code code then search all users for a matching field (stored on new user registration).
It seems all of this is to get around the fact that Firebase does not support a signInWithUsernameAndPassword (arbitrary userid/username) or even a signInWithUidAndPassword (Firebase UID). So we need Admin SDK workarounds, or Firebase Functions, and the serverless aspect of Firebase is seriously weakened.
For a 6-minute video on the topic of custom auth tokens, I strongly recommend Jen Person's YouTube video for Firebase here:
Minting Custom Tokens with the Admin SDK for Node.js - Firecasts
As of now in Firebase console, there is no direct API to get a list of users, Auth User(s) UID.
But inside your Firebase database, you can maintain the User UID at user level. As below,
"users": {
"user-1": {
"uid": "abcd..",
....
},
"user-2": {
"uid": "abcd..",
....
},
"user-3": {
"uid": "abcd..",
....
}
}
Then you can make a query and retrieve it whenever you need uid's.
Hope this simple solution could help you!
From Firebase docs, use Firebase.getAuth():
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
var authData = ref.getAuth();
if (authData) {
console.log("Authenticated user with uid:", authData.uid);
}
Source:
Firebase.getAuth()
I have a FireBase db with a users store. I also use simple login email/pw. In the User store I save some extra info of a user - e.g. the lastlogin date. This is my workflow - from registering to logging in:
I register a user;
when registered it is added to the simple login email/pw sote;
I also add the registered user (includng the id returned from the simplelogin) in the users store. It is stored under a Firebase generated unique key.
I log in as that new user
When successful I get a user object from the simplelogin store:
email-"testuser1#test.com"
firebaseAuthToken-"eyJ0eXAiOiJKV1QiLCJhbGci...SoXkddR3A88vAkENCy5ilIk"
id-"46"
isTemporaryPassword-false
md5_hash-"6a4b6cb2045fd55f706eaebd6ab5d4f7"
provider-"password"
uid-"simplelogin:46"
Now I want to update the corresponding user in the User store - e.g. set the lastlogin key to now. But I only can update that user when I know the Firebase generated key it's under. How can I access that key?
The only other way to identify the user in the Users store is by retrieving all users in the Users store, looping through all of them and checking : does the current id key value match the id key value of the logged-in user. Looks a bit clumsy to me but I fear this is the only way I can do lookups with firebase?
When you save a registered user you should save them by their uid rather than a generated id. This way when the user logs back in we'll user the uid to get the user from the users node.
var fbRef = new Firebase('https://<YOUR-FIREBASE>.firebaseio.com');
var auth = new FirebaseSimpleLogin(fbRef, function(error, user) {
if (error) {
console.error(error);
} else if (user) {
// when a user logs in we can update their lastLogin here
// set the key to the uid for the user
// this would look like: https://myapp.firebaseio.com/users/1
fbRef.child('users').child(user.uid).update({
lastLogin: Firebase.ServerValue.TIMESTAMP // the time they logged in
});
}
});
// here when we create a user we will set the key to the uid under the users node
auth.createUser(email, password, function(error, user) {
// if there is no error
if (!error) {
// go to the users node, then set a location at the user's uid
// this would look like: https://myapp.firebaseio.com/users/1
fbRef.child('users').child(user.uid).set(user);
}
});
As the users are created our users node will look like this: