Reputation: 95
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!
Upvotes: 5
Views: 3210
Reputation: 21
I'm not that experienced jet, but this has worked for me, but I'm not sure if it is the best way. I simply gave my body an id and added this JavaScript code:
var auth = firebase.auth();
auth.onAuthStateChanged(function(user) {
if (user) {
document.getElementById('homeBody').style.visibility = "visible";
} else {
document.getElementById('homeBody').style.visibility = "hidden";
}
});
I think this will do it for the starting companies. As your business grows, I recommend that you consider taking more security
Upvotes: 0
Reputation: 4349
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.
}
});
Upvotes: 3