简体   繁体   中英

How to redirect if User Is NOT logged-in in Firebase

I have a question that I do not believe has been answered before. I am currently looking for something in Firebase similar to a PHP session.

You see, when I log out of my web app, the user is redirected back into the login page like they should be. However, they are still able to type in direct URLs such as home.html and bypass the login screen.

I am wondering how this can happen if onAuthStateChanged is being called when the page loads up. It would make sense for them to be redirected immediately, similar to a session. Unfortunately, they are not.

This is the code that login.html and dashboard.html call when they are loaded. Can anybody spot mistake that could cause this issue? Thanks!

App.js

(function(){
const config ={
apiKey: " :) ",
authDomain: " :)",
databaseURL: " :) ",
storageBucket: " :)",
messagingSenderId: ":)"
};
firebase.initializeApp(config);
  //Grab Login Elements
const loginBtn = document.getElementById('sign-in-btn');
const emailTxt = document.getElementById('user-email');
const passTxt = document.getElementById('user-password');


//Set the click event to sign the user in
loginBtn.addEventListener('click', e => {
const email = emailTxt.value;
const password = passTxt.value;
const auth = firebase.auth();
//Actually Sign In
const promise = auth.signInWithEmailAndPassword(email, password);
promise.catch(e=> console.log(e.message));
});
//Realtime Authstate Listener

firebase.auth().onAuthStateChanged(firebaseUser => {
    if(firebaseUser){
        window.location = 'dashboard.html'
    }else{
        window.location = 'login.html'
    }
});
}());

Here are the important parts of dashboard.html

<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" type="text/css" href="styles/dashboardstyle.css">
<script src="https://www.gstatic.com/firebasejs/3.6.4/firebase.js"></script>
<body>
<script type="text/javascript" src="scripts/app.js"></script>
<script type="text/javascript" src="scripts/dashboard.js"></script>
</body>
</html>

It would make sense for onAuthStateChanged to fire, realize that the user is not logged in, and redirect, right? Any ideas? Thanks all!

That is a very good question. It depends how your infrastructure is set up.

If you are using Firebase real time database, you can use the firebase rules to restrict access to resources and use an onAuthStateChanged listener on each page and redirect to sign in when the user is not signed in.

If you are using your own backend, on sign in, you will save your own session cookie. The easiest thing to do is to save the firebase id token (getToken). You will need to keep refreshing this every hour (getToken(true)) as the token expires every hour and refresh your session cookie. In your backend, you can use the admin node.js library to verify the id token before serving a restricted resource and redirect to the login page if the user is not logged in. I realize this is somehow a simplification of the problem but should guide you in the right direction. The Firebase team has been notified of this problem and is looking into it.

I solved this issue by creating a nested if statement within the true portion of the original. Within this new if statement I checked the location of the user and, if they were on the login page, they were redirected using the existing code. I also had else if clauses in here to check for other locations of the user. For example, if they were on a page named profile.html , and the user exists, then I would not have to redirect them. This was checked by using the code

else if(window.location.href == 'http://website.com/profile.html`){
/*then do nothing, no need to be redirected because the user exists, as they 
are within a permitted page */
    }

This solved my problem.

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'

export default function PrivateRoute({ component: Component, ...rest }) {

    const { currentUser } = useAuth()

    return (
        <Route
            {...rest}
            render={props => {
                return currentUser ? <Component {...props} /> : <Redirect to='/login' />
            }}
        ></Route>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM