Created
December 7, 2015 23:38
-
-
Save shadowcodex/dcfe7d11b2e8cb0ca51d 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
} |
i found another way to do it let userData = firebase.auth().currentUser; if(userData.metadata.creationTime === userData.metadata.lastSignInTime){ console.log("user for the first time") }else{ console.log("user already present") }
Used this one.. clean and work perfect 😄
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks