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.
Related
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.
I have .js file where I loop through Firebase real time database to find email and password of registered users which is stored under /users tree in database where each child is randomly generated unique id which has user information. I am getting email and password information from form element. Problem is the alert messages in checkMessage are not executed when email and password do not equal same. Alert message should be displayed but only page refreshes.
Database:
----/Users
--------/XJIGFDMDKGD
-------------email: "a#b.com"
-------------password: "12345"
--------/XJFGNRIENGJ
-------------email: "c#d.com"
-------------password: "67890"
My code:
document
.getElementById('loginForm')
.addEventListener('submit', formSubmit);
function formSubmit(e) {
e.preventDefault();
document.querySelector('.alert').style.display = 'block';
// Get Values from the DOM
let email = document.querySelector('#email').value;
let password = document.querySelector('#password').value;
//check message values
checkMessage(email, password);
//Form Reset After Submission
//document.getElementById('loginForm').reset();
}
checkMessage function:
function checkMessage(email, password) {
var usrs = firebase.database().ref('users');
usrs.on("child_added", function(snapshot) {
var user = snapshot.val();
if (user.email == email) {
if (user.password == password) {
} else {
}
} else {
document.querySelector('.alert2').style.display = 'block';
setTimeout(function() {
document.querySelector('.alert2').style.display = 'none';
}, 7000);
document.getElementById('loginForm').reset();
}
);
}
The error was caused by syntax problem, an extra brace at the end of the following section of code, as well as a misplaced parentheses. Fixed solution:
var users = firebase.database().ref('users');
users.on("child_added", function(snapshot) {
var user = snapshot.val();
if (email == user.email) {
if (password == user.password) {
}
} else {
};
});
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
});
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.
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