How to keep user logged in with Firebase no matter what? - javascript

I am developing an app under the Ionic Framework and I am also using Firebase.
Now, it happens that after a few hours or for a crash of the app or restarting the device, the Authentication is lost.
How can I manage to have my user ALWAYS logged in, no matter what happen ? (Like Facebook for example)
Here is my Login Controller from the page login.html :
.controller('loginController',['$scope', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $firebaseArray, CONFIG, $document, $state) {
// Perform the login action when the user submits the login form
$scope.doLogin = function(userLogin) {
if($document[0].getElementById("user_name").value != "" && $document[0].getElementById("user_pass").value != ""){
firebase.auth().signInWithEmailAndPassword(userLogin.username, userLogin.password).then(function() {
var userId = firebase.auth().currentUser.uid;
firebase.database().ref('accounts/' + userId + '/currentBusiness/').update({
name: "No current business arround",
description: "Seems there's nothing arround...",
})
$state.go("tab.favorites");
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/invalid-email') {
alert('Enter a valid email.');
return false;
}else if (errorCode === 'auth/wrong-password') {
alert('Incorrect password.');
return false;
}else if (errorCode === 'auth/argument-error') {
alert('Password must be string.');
return false;
}else if (errorCode === 'auth/user-not-found') {
alert('No such user found.');
return false;
}else if (errorCode === 'auth/too-many-requests') {
alert('Too many failed login attempts, please try after sometime.');
return false;
}else if (errorCode === 'auth/network-request-failed') {
alert('Request timed out, please try again.');
return false;
}else {
alert(errorMessage);
return false;
}
});
}else{
alert('Please enter email and password');
return false;
}//end check client username password
};// end $scope.doLogin()
}])

I will answer my own question because I found the solution :
In my case, you have to use this code :
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
$state.go("tab.favorites");
// User is signed in.
} else {
// No user is signed in.
}
});

Try to store Login in a sharedPreferences or with an external resources once logged in, and then remove value when an user logs out.

Related

I need to maintain a user login in firebase

I have a page that autheticate the login, but i have two types of users, one adm e other a shopkeeper, after login, they are redirect to their respective pages, how can i maintain their login after redirect the pages after logging? I'm using firebase.
i'm trying to use persistence, but i dont know how it works properly.
$("#btnLogin").click(function(){
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function(){
var email = $("#inputEmail").val();
var senha = $("#inputSenha").val();
if(email != "" && senha != ""){
var login = firebase.auth().signInWithEmailAndPassword(email, senha);
login.then(function(result){
window.location.href = "";
}).catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert("não foi possível conectar");
console.log(errorMessage);
});
}else{
window.alert("Preencha todos os campos!");
}
}).catch((error)=>{
var errorCode = error.code;
var errorMessage = error.message;
alert("Erro percistencia");
console.log(errorMessage);
});
});
To keep an active session, we usually save a token in the "local storage" and make a request to the server to check if the token is linked to a user.

firebase.auth() error in createusermethod in java Script

This is my java script for Register page for web using firebase authentication.When i fill the email and password till Alert message Testing will execute but firebase.auth()..... it will not execute and the page will get refresh automatically.
var email=document.getElementById("inemail").value;
var password=document.getElementById("inpass").value;
var password1=document.getElementById("inpass1").value;
var lPassword=password.length;
var lPassword1=password1.length;
if(lPassword < 7)
{
alert("Password Should more than seven Charecter");
return;
}
else if(password!=password1){
alert("Correctly Enter the Password");
return;
}
else if(password==password1 || lPassword1==lPassword)
{
alert("Testing");
firebase.auth().createUserWithEmailAndPassword(email.toString(),password.toString()).catch(function(error) {
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);
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var email = user.email;
alert("Sucessfully Created");
}
else {
alert("sorry Try again");
}
});
}
}
in This script have any errors?if it have error please help me to find-out.
As Ticherhaz explains in his comment, your need to use the then() method to detect when the Promise returned by the asynchronous createUserWithEmailAndPassword() method is fulfilled.
The following should do the trick:
firebase.auth().createUserWithEmailAndPassword(email.toString(),password.toString())
.then(userCredential => {
var email = userCredential.user.email;
alert("Sucessfully Created");
})
.catch(function(error) {
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);
});
}
Note that, as explained in the doc, "on successful creation of the user account, this user will also be signed in to your application", so you don't need to use the onAuthStateChanged() method in this case.
In one of your comments above you say "only till alert message 'testing' this script is executing". Actually, if there is no error with the new user creation, the rejection handler callback passed to catch() is not called and therefore you don't get a feedback on the fact that the createUserWithEmailAndPassword() was correctly executed. For that you need the then() method.

firebase login wrong password

I need help, i keep getting an error where, whenever i log in it keeps saying wrong password even though i typed it correctly, registering the account is fine and it auto logs in but the moment i sign out the account, refresh and then log in it keeps saying wrong password, can anyone help me with this?
function loginbtn(){
//[then signs in the new user]
var loginEmail = document.getElementById('txtEmail').value;
var loginPass = document.getElementById('txtPass').value;
if (loginEmail.lenght <= 0){
alert('Please enter an email address.');
}
if (loginPass.lenght <= 0){
alert('Please enter a password.');
}
// Sign in with email and pass.
firebase.auth().signInWithEmailAndPassword(loginEmail, loginPass).catch(function(error){
// Handle Errors here.
var errorCode = error.code;
var errorMsg = error.message;
// [START_EXCLUDE]
if (errorCode ==='auth/wrong-password'){
alert('Wrong password.');
} else {
alert(errorMsg);
}
console.log(error);
document.getElementById('btnLogin').disabled = false;
});
// [END authwithemail]
//disables the button after logging in
document.getElementById('btnLogin').disabled = true;
}
This is the right way to signin correctly:
firebase.auth().signInWithEmailAndPassword(loginEmail , loginPass)
.then(function(firebaseUser) {
// Success
})
.catch(function(error) {
// Error Handling
});

Stripe error: The users credit card failed

I'm using Stripe to handle payments on my website. But, when I try to make a payment I'm getting a 'The users credit card failed' error. I've used this code on different sites and they work but, for some reason it isn't working here. Does anyone know what the problem might be? There definitely is money on the card:
function stripeResponseHandler(status, response)
{
if (response.error)
{
// Stripe.js failed to generate a token. The error message will explain why.
// Usually, it's because the customer mistyped their card info.
// You should customize this to present the message in a pretty manner:
alert(response.error.message);
}
else
{
// Stripe.js generated a token successfully. We're ready to charge the card!
var token = response.id;
var email = $("#email").val();
var price = $("#price").val();
var id = $("id").val();
// Make the call to the server-script to process the order.
// Pass the token and non-sensitive form information.
var request = $.ajax ({
type: "POST",
url: "pay.php",
dataType: "json",
data: {
"stripeToken" : token,
"email" : email,
"price" : price,
"id" : id
}
});
request.done(function(msg)
{
if (msg.result === 0)
{
// Customize this section to present a success message and display whatever
// should be displayed to the user.
window.location.replace("http://foo.com");
}
else
{
// The card was NOT charged successfully, but we interfaced with Stripe
// just fine. There's likely an issue with the user's credit card.
// Customize this section to present an error explanation
alert("The user's credit card failed.");
}
});
request.fail(function(jqXHR, textStatus)
{
// We failed to make the AJAX call to pay.php. Something's wrong on our end.
// This should not normally happen, but we need to handle it if it does.
alert("error");
});
}
}
function showErrorDialogWithMessage(message)
{
// For the tutorial, we'll just do an alert. You should customize this function to
// present "pretty" error messages on your page.
alert(message);
// Re-enable the order button so the user can try again
$('#buy-submit-button').removeAttr("disabled");
}
$(document).ready(function()
{
$('#buy-form').submit(function(event)
{
// immediately disable the submit button to prevent double submits
$('#buy-submit-button').attr("disabled", "disabled");
var fName = $('#first-name').val();
var lName = $('#last-name').val();
var email = $('#email').val();
var cardNumber = $('#card-number').val();
var cardCVC = $('#card-security-code').val();
// First and last name fields: make sure they're not blank
if (fName === "") {
showErrorDialogWithMessage("Please enter your first name.");
return;
}
if (lName === "") {
showErrorDialogWithMessage("Please enter your last name.");
return;
}
// Validate the email address:
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
showErrorDialogWithMessage("Please enter your email address.");
return;
} else if (!emailFilter.test(email)) {
showErrorDialogWithMessage("Your email address is not valid.");
return;
}
// Stripe will validate the card number and CVC for us, so just make sure they're not blank
if (cardNumber === "") {
showErrorDialogWithMessage("Please enter your card number.");
return;
}
if (cardCVC === "") {
showErrorDialogWithMessage("Please enter your card security code.");
return;
}
Stripe.createToken({
number: cardNumber,
cvc: cardCVC,
exp_month: $('#expiration-month').val(),
exp_year: $('#expiration-year').val()
}, stripeResponseHandler);
// Prevent the default submit action on the form
return false;
});
});
Thanks in advance

If Statement Not Acting As Expected

$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.

Categories

Resources