Reputation: 1365
I'm fairly new to node and making a web-app in which I use passport to authenticate and then store the user using firebase authentication by a custom token.
and now i want to perform a lookup and check if the user is registered with my app.
So is there is a way to check for a specific user (like either by their uid or email)?
in the docs here it is given how to list all the users.
here is the code for it (i modified a bit for my purpose) -
function listAllUsers(id, nextPageToken) { // passing an id to check and page token is not passed as default
// List batch of users, 1000 at a time.
admin.auth().listUsers(1000, nextPageToken)
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
if (userRecord.uid == id){
return true // here i return from the function but it only return from one function. (do i have to make a flag to come out from all of them?)
}
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(id, listUsersResult.pageToken)
}
})
.catch(function(error) {
console.log("Error listing users:", error);
});
}
// Start listing users from the beginning, 1000 at a time.
let user = listAllUsers('some random id'); // i expect a Boolean here
but is there any way to do a lookup like listUsersResult.users.find(id) // which may return a boolean or whole user?
Upvotes: 1
Views: 2409
Reputation: 4202
Looking at the docs you linked and having played around a little in firebase myself, there is no method that returns a found/not found boolean. However, you can do:
admin.auth().getUser(uid)
.then(function(userRecord) {
// See the UserRecord reference doc for the contents of userRecord.
console.log("Successfully fetched user data:", userRecord.toJSON());
})
.catch(function(error) {
console.log("Error fetching user data:", error);
});
As quoted by their docs:
If the provided
uid
does not belong to an existing user or the user cannot be fetched for any other reason, the above method throws an error.
If you want a boolean simply set a boolean in the then...catch
to whether the user was found or not.
For example:
let found = false;
admin.auth().getUser(uid)
.then(function(userRecord) {
found = true;
})
.catch(function(error) {
found = false;
});
EDIT
To return to your base function, the best way (in terms of Node) is to make the function asynchronous with a callback/Promise/Observable. As Promise's are newer I will create one here:
var user_check = new Promise(function(resolve, reject) {
admin.auth().getUser(uid)
.then(function(userRecord) {
resolve(userRecord);
})
.catch(function(error) {
reject(error);
});
});
console.log(user_check); // if found, returns the user_record, else, returns an error
For more information regarding async code, refer to MSDN
Upvotes: 4
Reputation: 317487
See the documentation. You can call admin.auth.getUser(uid)
for this (also see the API docs).
Upvotes: 1