Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Restrict Access to other pages without user logged in

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!

like image 871
Duckbenok Avatar asked Oct 18 '22 07:10

Duckbenok


1 Answers

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.
  }
});
like image 144
Abdelaziz Mokhnache Avatar answered Oct 20 '22 00:10

Abdelaziz Mokhnache