javascript - Firebase Restrict Access to other pages without user logged in -


i have index.html page redirect home.html after correct login. have solved login , logout part. problem can access home.html directly on url without logging in.

here snippet of 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 on beginning of home.html if page accessed directly return index. worked on redirecting index.html when login correctly, still redirects me index.html

it seems firebase gets auth fast cannot initialize currentuser values giving null result. suggestion on how restrict direct access using url help.

thanks!

try using firebase.auth().onauthstatechanged instead of firebase.auth().currentuser; recommended way current user.

getting user currentuser may cause problem similar seeing. official doc of firebase.

note: currentuser might null because auth object has not finished initializing. if use observer keep track of user's sign-in status, don't need handle case.

try current user this:

firebase.auth().onauthstatechanged(function(user) {   if (user) {     // user signed in.   } else {     // no user signed in.   } }); 

Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -