Google firebase web: User authentication and database write - javascript

I have just started with firebase for my webapp and here is my code and problem beneath.
<script src="https://www.gstatic.com/firebasejs/4.1.2/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.1.1/firebase-database.js"></script>
<script>
// Initialize Firebase
var config = {
...
};
firebase.initializeApp(config);
</script>
<script>
function handleSignUp() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
function initApp() {
document.getElementById('quickstart-sign-up').addEventListener('click', handleSignUp, false);
}
window.onload = function() {
initApp();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('yes');
I want data persistence in firebase database at this step.
} else {
console.log('no');
}
});
};
</script>
Problem is whenever I am refreshing my page, as the user is authenticated, console returns Yes (when I am adding the database push logic, data is being saved again and again whenever I am refreshing the page. I have tried moving the console.log OR database push to .onAuthStateChange to my initApp() and handleSignUp() functions as well. But to no avail.
As per firebase docs, I tried the below as well:
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
However, this almost always returns a console.log as No. I am thinking that since it takes some time for the authentication to happen, the user check is skipping authentication and appearing as if No user is authenticated.
The ask is I want the user to be signed up (and automatically logged in which happens anyway with firebase) and user details (along with additional details which I am asking the user to fill in at Sign Up) to be saved in firebase database one time only. Any pointer would be appreciated here.

Think I got it. The use of then (promises):
firebase.auth().createUserWithEmailAndPassword(email, password).then(function() {
var user = firebase.auth().currentUser;
console.log(user.email);
}).catch(function(error)
As soon as user is created, the function will act (will do the data persistence in the database) and since it is not dependent on user auth'ed or not, along with unique emails, this step would never be repeated, hence single time data save in database. Had gone through the docs multiple times, somehow missed it. Apologies guys.

Related

clear the current session after closing the tab or browser in the Firebase real-time database in Javascript

I want to log out the current session after closing the tab or browser in the Firebase real-time database in Javascript.
If I log in with my email address and password, copy the URL and paste it into a new tab, it always shows the current page instead of the login screen or (session logout). It should log out my current session when the state change when I close the tab, close the browser, or open the same page in a new tab it should always show a login screen.
function login() {
var email = document.getElementById("email");
var password = document.getElementById("password");
firebase.auth().signInWithEmailAndPassword(email.value, password.value)
.then((result) => {
alert("Login Successful");
console.log(result);
if (email.value == "abc123#gmail.com") {
window.location.href = "dpr.html"
} else if (email.value == "abc1234#gmail.com") {
window.location.href = "gpr.html"
} else if (email.value == "abc12345#gmail.com") {
window.location.href = "cargo.html"
} else if (email.value == "abc123456#gmail.com") {
window.location.href = "admin.html"
}
})
.catch(function (error) {
var errorCode = error.code;
console.log(errorCode);
var errorMessage = error.message;
alert("Please Enter the correct password")
})
}
Firebase Authentication keeps the user's authentication state in local storage. If you want to prevent it from doing that, you can set the auth state persistence behavior. To have the auth state only be persisted to the current session, you'd do:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
See the documentation I linked above for a full explanation.

Console says onsubmit function doesn't exist for register form, even though it clearly does

So I have a register form, as thus:
<form name="register" action="" method="POST" onsubmit="register()" autocomplete="off">
...
</form>
And I know that every child of this form is functioning.
Then, below in a <script> tag I have my main function which is called when the above form is submitted. And I know that everything outside of the register function is running. However, when I input random values into each field of my form, and press submit, the console shows that the register() function called in the onsubmit attribute of my form does not exist. I can't seem to find the problem here:
//Global Vars
var firebaseConfig = { ...
};
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
var registerButton = document.querySelector("#registerButton");
//Main Register Function
function register() {
event.preventDefault();
//Locally Global Variables
var fullName = document.forms["register"]["fullName"].value;
var username = document.forms["register"]["username"].value.toLowerCase();
//The MD5 is a way to hash the password, that way the real password is safe and only the hash is used
var password = md5(document.forms["register"]["password"].value);
var serviceProvider = document.forms["register"]["serviceProvider"].value;
//Simple If Statement that adds appropriate email suffix based on Service Provider
if (serviceProvider === "Verizon") {
serviceProvider = "#vtext.com";
} else if (serviceProvider === "ATT") {
serviceProvider = "#txt.att.net";
} else if (serviceProvider === "TMobile") {
serviceProvider = "#tmomail.net";
} else if (serviceProvider === "Sprint") {
serviceProvider = "#messaging.sprintpcs.com";
}
var phoneNumber = document.forms["register"]["phoneNumber"].value + serviceProvider;
var emailAddress = document.forms["register"]["emailAddress"].value;
//Checks The Database If The Username Is Already Taken Or Not
db.collection("Users").where("username", "==", username).get()
.then(function(querySnapshot) {
//Checks Each Individual Result -- If there are no results, than this code will not run
try {
querySnapshot.forEach(function(doc) {
//If any result exists, stop here
if (doc.data()) {
alert("I'm sorry but this username is already taken!! Please Try Another One");
throw "Error";
}
});
} catch (error) {
if (error === "Error") {
return;
}
}
//If not
//Add All Of The User Info To The Database
db.collection("Users").doc(username).set({
fullName: fullName,
username: username,
password: password,
phoneNumber: phoneNumber,
emailAddress: emailAddress,
chatsInvolvedIn: []
})
.then(function() {
//If it succeeds, give user the heads up and then take them to their new homepage
alert("Your account under the username " + username + " has been sucessfully created. You will now be redirected to your homepage.");
//Place Code Underneath to Handle Keeping user Logged In For Present and Future Visits, along with redirecting to a homepage
//Code Goes Here
db.collection("Users").doc(username).get().then(function(doc) {
if (doc.exists) {
localStorage.setItem("loggedIn", JSON.stringify(doc.data()));
}
alert(localStorage.getItem("loggedIn"));
//window.location.replace("index.html");
});
})
.catch(function(error) {
//If it fails, tell user to try again later (we don't care about the error message during production, because it is unlikely after our many tests)
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
})
.catch(function(error) {
//If checking the database originally for duplicate usernames fails, then give the user the same warning as above
alert("I'm sorry but your account was not successfully created due to an unexpected error. Please try again later.");
});
}
I know that my programming practices above aren't the best. if you could help me out, that would be great, thank you!

I am using Firebase authentication for my application. There seems to be an infinite loop where the page keeps being redirected over and over again

The following function is to redirect the user to "Select Stream.html" when the user logs in.It keeps on replacing the location over and over again.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
window.location.replace("Select Stream.html");
// User is signed in.
} else {
// No user is signed in.
window.location.replace("index.html");
}
});
I am new to coding.
Here is the Log in Function
function login()
{
var userEmail=document.getElementById("email-field").value;
var userPassword=document.getElementById("password-field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
/* window.location='Select Stream.html'; */
window.alert("Error : " + errorMessage);
// ...
});
}
The Login function will be triggered when the signin-button is clicked.
<input onclick="login()" type="submit" name="signin-button" value="Sign In"/>
First, change the name of Select Stream.html to have no spaces or capital letters. This is common practice, and I recommend changing the name of the file to select_stream.html.
Before opening select_stream.html or index.html, check whether the user is already on that page to prevent the page from refreshing, like this:
if (user) {
// User is signed in.
if(window.location.href.indexOf("select_stream.html") == -1){
window.location.replace("select_stream.html");
}
} else {
// No user is signed in.
if(window.location.href.indexOf("index.html") == -1){
window.location.replace("index.html");
}
}
The window.location.href variable refers to the URL of the current page, and the .indexOf function allows you to check if a value is contained inside the URL. The .indexOf function returns -1 if the specified value could not be found within the string, so this code simply only redirects if the user is not already on the redirect page.

Regularly signed out when using firebase authWithPassword

I have a phonegap app on iOS using firebase for authentication. Logging in is done like so:
var afterLogin = function(error, authData) {
if (error) {
console.log(error);
messenger.error(error.message);
return;
}
$scope.loggedIn = $auth.check();
$scope.$apply();
$sync.sync();
messenger.success('Logged in');
};
$scope.doLogin = function() {
mixpanel.track('login');
if (!$scope.loginForm.email && !$scope.loginForm.password) {
messenger.error('Enter email and password then tap login');
return;
} else if (!$scope.loginForm.email) {
messenger.error('Enter your email then tap login');
return;
} else if (!$scope.loginForm.password) {
messenger.error('Enter your password then tap login');
return;
}
ref.authWithPassword({
email : $scope.loginForm.email,
password : $scope.loginForm.password
}, afterLogin);
}
I check a user's status like this:
check: function() {
var authData = ref.getAuth();
if (authData) {
mixpanel.identify(authData.uid);
mixpanel.people.set({
"$email": authData.password.email
});
}
return !!authData;
}
It works fine initially, but users get signed out and have to log in again after 12-24 hours of not using the app. Perhaps when the app is shunted out of memory? Obviously this is pretty frustrating, not sure what's causing this. The session length is set to 24 weeks, still having the problem.
Firebase version: 2.1.2
Angular: 1.3.6
Log of localStorage after authenticating with username and password:
Coming back a day later after being logged out:
Contents of the cookie (same logged in or not, no firebase stuff in there):
It's a parameter in Firebase.
Go on the Dashboard of the Firebase.
Click on "Login & Auth".
Then in the first paragraph, there is an input and select for the Session Length. You can choose how many hours/weekks, etc you want.

Facebook Javascript, How to detect if user is a fan of my facebook page? While on my site?

I have the following JS code.
The code's purpose is to first get the users facebook id, and then using FQL check that id against my page ID and make sure the user is a fan.
The problem I am running into is that the only time the code actually works is if i login with my own personal facebook profile. I think its because my profile and the FB.init appid are somehow linked?
Can someone take a look at this code and show me where I am going wrong?
My goal again is to use JS to first get the users id (thus their thumbnail image), and then cross reference that against my own facebook page to check and see if they are a fan. If they are a facebook fan, then I will probably give them a coupon or something.
Thanks in advance.
<script src="http://connect.facebook.net/en_US/all.js"></script>
//Connect to facebook with my app id..
FB.init({
appId:'135445813195028',
cookie:false,
status:true,
xfbml:true
});
//Check to see if user is actually CONNECTED???
FB.getLoginStatus(function(response) {
if (response.session) {
// USER IS CONNECTED
FB.api('/me', function(user) {
if (user != null) {
var image = document.getElementById('imagez');
image.src = 'http://graph.facebook.com/' + user.id + '/picture?type=large';
var name = document.getElementById('name');
name.innerHTML = user.name;
FBID = user.id;
console.log('Facebook ID:' + FBID);
//assemble an FQL query to see if the guy is a fan of our page...
myquery = 'SELECT uid FROM page_fan WHERE page_id = 126923080686340 AND uid = ' + FBID;
console.log('query = ' + myquery);
///Run FQL Query to see if user is a fan
FB.api({
method: 'fql.query',
query: myquery
}, function(resp) {
if (resp.length) {
var IsFan = true;
alert('You are A fan!')
console.log('Visitor is a fan');
//show coupon code...
} else {
alert('Signed into facebook, but Not a fan!');
var IsFan = false;
console.log('Visitor is not a fan');
//show like button...
//once like is clicked then refresh the page...
}
});
//END Run FQL Query to see if user is a fan
}
});
//Figure out if they are a fan...
} else {
// USER IS NOT CONNECTED
alert('NO USER session, user is not logged into facebook!!!');
}
});
The FB.getLoginStatus check to see if the user is connected to your application .. not to facebook.
But when the user is not connected to your application, the .status property can tell you the reason of the fail (if the user is not logged-in at all, or just to your app).
So the structure you should use is
FB.getLoginStatus(function(response) {
if(response.session) {
alert('connected to Application');
} else {
// no user session available, someone you dont know
if(response.status == "notConnected") {
// But user is logged into facebook
alert("Not connected to Application, but is logged in to Facebook");
} else {
// User is not logged into facebook
alert('Not logged in to facebook');
}
}
});
But you cannot access the ID of a user that has not authorized your Application.
Not through Javascript API.

Categories