Instantly share code, notes, and snippets.

Embed
What would you like to do?
Methods to search for user accounts by email address in Firebase
/***************************************************
* Simple and elegant, no code complexity
* Disadvantages: Requires warming all data into server memory (could take a long time for MBs of data or millions of records)
* (This disadvantage should go away as we add optimizations to the core product)
***************************************************/
var fb = firebase.database.ref();
/**
* @param {string} emailAddress
* @return {Object} the object contains zero or more user records, the keys are the users' ids
*/
function findUsersMatchingEmail( emailAddress, callback ) {
fb.child('user').orderByChild('emailAddress').equalTo(emailAddress).once('value', function(snap) {
callback( snap.val() );
});
}
/***************************************************
* Useful for MBs or more of data, or lists of thousands or more records
* Disadvantages: Slight code complexity due to two queries (one for key, another for record); escaping emails is annoying
***************************************************/
var fb = firebase.database.ref();
/**
* Looks up a user id by email address and invokes callback with the id or null if not found
* @return {Object|null} the object contains the key/value hash for one user
*/
function getUserIdByEmail( emailAddress, callback ) {
fb.child('emails_to_ids/'+emailToKey(emailAddress)).once('value', function(snap) {
callback( snap.val() );
});
}
/**
* Creates a new user record and also updates the index
*/
function createNewUser( userRecord ) {
var uid = fb.child('user').push().key();
// do a multi-path write!
var mergedData = {};
mergedData['users/' + uid] = userRecord;
mergedData['emails_to_ids/'+emailToKey(userRecord.email)] = uid;
fb.update(mergedData);
return id;
}
/**
* Firebase keys cannot have a period (.) in them, so this converts the emails to valid keys
*/
function emailToKey(emailAddress) {
return emailAddress.replace(/[.]/g, '%20');
}
@mikemurray

This comment has been minimized.

mikemurray commented Sep 27, 2014

A quick update for the emailToKey function. Using a global regex match on the period, for those that have emails like first.last@gmail.com, will replace all periods, not just the first instance.

// Only the 1st period gets replaced
"y.u.no.work@gmail.com".replace('.', ',')
// RESULT: "y,u.no.work@gmail.com"

// All periods get replaced
"y.u.no.work@gmail.com".replace(/\./g, ',')
// RESULT: "y,u,no,work@gmail,com"
@Hectorsito20

This comment has been minimized.

Hectorsito20 commented Oct 12, 2014

nice

@al-the-x

This comment has been minimized.

al-the-x commented Dec 8, 2014

Consider hashing the email address to completely avoid the problem of invalid characters. Base64 encoding is baked into JavaScript. Since it's reversible, it's technically not cryptographic but more convenient than importing a SHA1 / MD5 library. For example:

function emailToKey(emailAddress){
  return btoa(emailAddress);
}
@bridgkick

This comment has been minimized.

bridgkick commented Jan 9, 2015

Small thing: in createNewUser when supplying the key 'emails_to_ids/'+userRecord.email, does it do the conversion from periods to commas automatically? For noobs like me it would be good to put this in the comments or explicitly use emailToKey() for both the write and the lookup.

@freidamachoi

This comment has been minimized.

freidamachoi commented Jan 11, 2015

@al-the-x
+1 have found this method to be the most efficient - if you do use md5 it does allow for quick/easy use for Gravatar, but Base64 provides lower overhead.

@willurd

This comment has been minimized.

willurd commented Feb 24, 2015

@bridgkick emailToKey isn't getting called implicitly in createNewUser. I'm guessing this was just missed and createNewUser should actually read:

function createNewUser( userRecord ) {
   var id = fb.child('user').push(userRecord).name();
   fb.child('emails_to_ids/'+emailToKey(userRecord.email)).set(id);
   return id;
}
@morgs32

This comment has been minimized.

morgs32 commented Oct 15, 2015

Love the btoa solution. Can email addresses even have characters outside the latin1 range? @kristijanmatic @al-the-x

@jondthompson

This comment has been minimized.

jondthompson commented Nov 15, 2015

I'm guessing that the security rules for emails_to_ids would be:

"emails_to_ids":{
    "$email":{
        ".read":"<User has need to lookup id by email>",
        ".write":"<User has ability to create an email, or change the address of an email>"
    }
}

This would still allow the user to guess email addresses to look up IDs, but would not allow them to lookup the whole list, decode it, and be able to get the IDs from there.

If there is a need for the ID to remain secret, the only way would be a second table that has a second generated id to actual id lookup, and a server-side process that would handle the actions, but the rules on the actual user list should make the ID's secret irrelevant.

@jondthompson

This comment has been minimized.

jondthompson commented Nov 16, 2015

Actually, the path needs to be writeable for creating a new user, as well as anyone that wants to change their email address. This means that it has to be world writeable, thus world readable.

@katowulf

This comment has been minimized.

Owner

katowulf commented Mar 7, 2016

@mikemurray Addressed comments and updated for Firebase queries. Thanks!
@jondthompson world writable/readable isn't necessary. You can make paths editable only by the owner's uid.

@katowulf

This comment has been minimized.

Owner

katowulf commented Mar 7, 2016

@al-the-x hashes are a great answer but btoa isn't necassarily available cross-platform. It just requires including a hash function of some sort or a polyfill for btoa, so still a great choice.

@chromeragnarok

This comment has been minimized.

chromeragnarok commented May 20, 2016

This is awesome, thanks!

@marcovega

This comment has been minimized.

marcovega commented Dec 7, 2016

var uid = fb.child('user').push().key();
For me it's working as a prop and not a method, so .key instead of .key()

@choopage

This comment has been minimized.

choopage commented Jun 28, 2017

@nderkach

This comment has been minimized.

nderkach commented Dec 3, 2017

Now you can just do the following:

admin.auth().getUserByEmail(email)
  .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);
  });

See https://firebase.google.com/docs/auth/admin/manage-users for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment