Methods to search for user accounts by email address in Firebase.
An example of searching for user accounts by email address.
/***************************************************
* 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 = new Firebase(URL);
/**
* @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 = new Firebase(URL);
/**
* 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');
}
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);
}