I have an index.html page that will redirect to home.html after the correct login. I have solved the login and logout part. my problem is I can access home.html directly on the URL without logging in.
here is some snippet of my home.html
<script>
var config = {
apiKey: "xxxxxx",
authDomain: "firebaseapp.com",
databaseURL: "firebaseio.com",
};
firebase.initializeApp(config);
const auth=firebase.auth();
const db=firebase.database();
var user = firebase.auth().currentUser;
if (user) {
//blank if correct login
} else {
window.location.href = 'firebaseapp.com/index.html';
}
</script>
I put this on the beginning of my home.html so that if the page will be accessed directly it will return to the index. It worked on redirecting to the index.html BUT even when i login correctly, it still redirects me to the index.html
It seems like the firebase gets the auth too fast that it cannot initialize the currentUser values properly thus giving a null result. Any suggestion on how to restrict direct access using the URL would really help.
Thanks!
try using firebase.auth().onAuthStateChanged
instead of firebase.auth().currentUser;
it is the recommended way to get the current user.
Getting the user by currentUser
may cause a problem similar to what you are seeing. This is from the official doc of firebase.
Note: currentUser might also be null because the auth object has not finished initializing. If you use an observer to keep track of the user's sign-in status, you don't need to handle this case.
Try to get the current user like this:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With