Firebase auth automatically signs me back in after logout - javascript

My login function works fine but after logging out it redirects me back to my login landing page. The AuthState in the login js doesnt change is it a bug or do i have an error in my code.
Login.js
function loginBtn(){
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail,userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
console.log(error.Message);
window.alert("Error : " + errorMessage);
});
}
firebase.auth().onAuthStateChanged(user => {
if(user) {
window.location = '/home';
}
});
function recaptchaCallback() {
$('#submitBtn').removeAttr('disabled');
};
Auth.js
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
} else {
// No user is signed in.
firebase.auth().signOut();
alert('NOT LOGGED IN');
window.location='/';
}
});
function logout(){
firebase.auth().signOut();
alert('SIGNED OUT');
window.location='/';
}

I solved it by placing the OnAuthStateChanged to document ready since the listener is too slow to load.
$(document).ready(function(){
firebase.auth().onAuthStateChanged(user => {
if(user) {
window.location = '/home';
}
});
});

Related

Firebase web realtime database not updating

I am trying to update my firebase realtime database with user info when I am creating new user through firebase password authentication. And on successful sign in I am moving to another page. The problem is that my database is not getting updated in the above scenario however if stay in the login page and don't change to any other url; the database gets updated.
Here's my create user code
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
if (user !== null) {
const db = firebase.database();
db.ref("/").set({
uid: user.uid,
});
}
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
// ..
});
And here's where I'm switching to another page,
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
console.log(user);
//If I remove the below line, database is updated
window.location.href = "../html/home.html";
// ...
} else {
// User is signed out
// ...
console.log("not logged in");
}
});
This calls is asynchronous:
db.ref("/").set({
uid: user.uid,
});
That means that the code continues to run after the set() function returns, and asynchronously sends the data to the database. But when you change window.location, it interrupts this write operation. That's also why it works when you don't send the user to a new location: the write operation can then complete without interruption.
A quick simple fix is to flag when you're updating the database:
isCreatingUser = true; // 👈 Flag that we're creating a user
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
var user = userCredential.user;
if (user !== null) {
const db = firebase.database();
db.ref("/").set({
uid: user.uid,
}).then(() => {
isCreatingUser = false; // 👈 We're done
window.location.href = "../html/home.html"; // 👈 Navigate away
}).catch((e) => {
isCreatingUser = false; // 👈 We're done
throw e;
})
}
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
// ..
isCreatingUser = false; // 👈 We're done
});
And then:
firebase.auth().onAuthStateChanged((user) => {
if (user && !isCreatingUser) {
...
You'll probably need some more synchronization, but that's the gist of it.

firebase login authentication gives me that email must be a valid string

It always gives me "first argument (email) must be a valid string" and it doesn't login
i don't know if the problem is in the js code but im pretty sure it's not in the html .
and another question .. do i need the " onAuthStateChanged " function?
<script>
var rightAccount = 0;
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn();
function SignIn(email,password) {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
authStateListener();
rightAccount = 1;
//Signed in
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
alert(errorMessage);
});
};
function authStateListener() {
// [START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
currentUser = user;
console.log(currentUser.email + " has logged in")
} else {
// ...
}
});
// [END auth_state_listener]
};
if (rightAccount == 1) {
setTimeout(function Redirect() {
window.location.replace("Website/homePage.php");
}, 2000)
}
</script>
You must pass email and password values to function. Otherwise it will be give error.
...
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn(email, password); // <-- Here pass them
...

Can I call function in previous screen - react native?

I have a function "signInWithPhoneNumber" in SignUp screen after call it navigates me to a Confirmation Screen and I pass some params after navigate to confirm a verification code I was received,
So in this screen "Confirmation", I have a button "Re-send Verification Code" so my question is
when I press to "re-send" I want to call a "signInWithPhoneNumber" function in SignUp screen to get a new code
So what you think? that's possible?
Or rewrite a signInWithPhoneNumber in a confirmation screen and call it after pressed re-send button?
SignUp Screen - Function
signUp = async () => {
const {phoneNumber} = this.state;
this.setState({message: 'Sending code ...'});
const phoneWithAreaCode = phoneNumber.replace(/^0+/, '+972');
console.log(phoneWithAreaCode);
auth()
.signInWithPhoneNumber(phoneWithAreaCode, true)
.then(confirmResult => {
console.log('confirmResult', confirmResult);
this.setState({confirmResult, message: 'Code has been sent!'});
// this.createUserDatabase();
})
.then(() => {
this.props.navigation.navigate('Confirmation', {
message: this.state.message,
confirmResult: this.state.confirmResult,
createUser: uid => this.createUserDatabase(uid),
});
});
};
Confirmation screen - function
confirmCode = codeInput => {
const confirmResult = this.props.navigation.state.params.confirmResult
if (confirmResult && codeInput.length) {
confirmResult
.confirm(codeInput)
.then(user => {
clearInterval(this.interval);
const {params} = this.props.navigation.state;
//Check if any users exist
database()
.ref(`users`)
.limitToFirst(1)
.once('value', snapshot => {
if (snapshot.exists()) {
console.log('exists!');
return true;
} else {
params.createUser(user.uid);
console.log('No user found Hah');
}
});
this.setState({
timer: 0,
message: 'Code Confirmed!',
isValid: true,
});
})
.catch(error => {
let errorCode = error.code;
let errorMessage = error.message;
console.log(errorCode);
switch (errorCode) {
case 'auth/invalid-verification-code':
this.setState({message: 'Code is invalid', codeInput: ''});
this.refs.codeInputRef2.clear();
break;
default:
alert(`Please, Check your Messages!`);
break;
}
console.log(errorMessage);
});
} else {
console.log('Not here');
}
};
You can send signInWithPhoneNumber to Confirmation screen, while navigating to it from SignUp screen, like so
this.props.navigation.navigate('Confirmation', {
message: this.state.message,
confirmResult: this.state.confirmResult,
createUser: uid => this.createUserDatabase(uid),
signInWithPhoneNumber: signInWithPhoneNumber // your actual function here
});
});
And then this function will be available in Confirmation screen as a prop, and you can call it when necessary

Page refreshing repeatedly after login using firebase

After logging in, the page to which the user is redirected is refreshing repeatedly.
Here is the javascript code:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
window.location="comingsoon.html";
var user = firebase.auth().currentUser;
} else {
// No user is signed in.
}
});
function login(){
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
function logout(){
firebase.auth().signOut();
}
You have to unsubscribe from the event listening function onAuthStateChanged after you execute your code. To do this you can write :
const unsubscribeAfterAuth = firebase.auth().onAuthStateChanged(function (user) {
if (user) {
window.location="comingsoon.html";
var user = firebase.auth().currentUser;
} else {
// No user is signed in.
}
});
unsubscribeAfterAuth();
This way you won't get updates after the first onAuthStateChanged as your function won't be listening to the event after the first call.

Firebase: During testing I get "undefined is not a function"

This is my used code:
var cred = firebase.auth().EmailAuthProvider($scope.data.mail, $scope.data.pwd);
firebase.auth().signInWithCredential(cred)
.then(function()
During testing, I get the following error:
TypeError: undefined is not a function (evaluating
'firebase.auth().EmailAuthProvider($scope.data.mail,
$scope.data.pwd)')
So what's wrong with my code? How can I fix this problem?
To log a user in via email/pass you just call the signInWithEmailAndPassword method.
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
Then you can listen for the realtime auth event:
firebase.auth().onAuthStateChanged(function(user) {
if (user !== null) {
console.log('logged in!');
}
});
Check the docs here for more on email login.
Check the API reference for onAuthStateChanged for more info.
Fixed By:
const register = () => {
createUserWithEmailAndPassword(auth, email, password)
.then((auth) => {
setPass(1);
})
.catch((error) => alert(error.message));
};
console.log(pass);
if (pass === 1) {
updateProfile(auth.currentUser, {
displayName: name,
photoURL: image || "https://example.com/jane-q-user/profile.jpg",
})
.then(() => {
// Profile updated!
// ...
})
.catch((error) => {
// An error occurred
// ...
});
setPass(0);
}

Categories

Resources