Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibot17/ca766e766933a9f7069fe41f16ff548f to your computer and use it in GitHub Desktop.
Save guibot17/ca766e766933a9f7069fe41f16ff548f to your computer and use it in GitHub Desktop.
Firebase: Detecting if user exists.This snippet detects if a user ID already exists, in order to do first time user functions.
// Assuming you have included the firebase script tag above this javascript
// For reference here is the tag: <script src="https://cdn.firebase.com/js/client/2.3.2/firebase.js"></script>
// Assumes you have already authenticated the user.
// Setup your firebase reference
var ref = new Firebase('https://your-app.firebaseIO-demo.com/');
// Setup a way to get your userid (Assuming using provided firebase authentication method...)
function getUser(authData) {
switch(authData.provider) {
case 'password':
return authData.password.email;
case 'twitter':
return authData.twitter.username;
case 'facebook':
return authData.facebook.email;
case 'google':
return authData.google.email;
case 'github':
return authData.github.username;
}
}
// Get authentication data
var authData = ref.getAuth();
// Get your user information
var userid = getUser(authData);
// Call your function to check if they are a first time user (aka exists).
checkForFirstTime(userid);
// Setup what to do with the user information.
function userFirstTimeCallback(userId, exists) {
if (exists) {
alert('user ' + userId + ' exists!');
// Do something here you want to do for non-firstime users...
} else {
alert('user ' + userId + ' does not exist!');
// Do something here you want to do for first time users (Store data in database?)
}
}
// Tests to see if /users/<userId> exists.
function checkForFirstTime(userId) {
usersRef.child('users').child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userFirstTimeCallback(userId, exists);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment