How to show a different page if the user has registered through firebase

I have a little problem and it seems to be easy, but I can’t plunge into the head what to do.

I have an express application that uses Firebase to store data. I can log in, register and log out through the client side of the script, but my problem is: how can I check through express if the user is logged in to be able to send another page to registered users?

This is my code:

var firebase = require('firebase');
// Initialize Firebase
var config = {
 serviceAccount: "./Chat Application-ad4eaaee3fcc.json",
 databaseURL: "MY_DATABASE_URL"
};
firebase.initializeApp(config);

and then I want to show a special login page, and here is what I tried:

router.get("/special-page", function(req, res, next) {
    var user = firebase.auth().currentUser;
    console.log(user); // this variable gets undefined
    if(user) {
        res.render("special-page");
    } else {
        res.redirect("/");
  }
});

I know this may seem like an easy question, but any help would be much appreciated!

Thanks in advance.

+4
1

- . , , , , firebase.auth().currentUser , .

, .

, " XXX", , , .

- Firebase , firebase, 100% .

, React , .

  • cookie, firebase
  • cookie,
  • cookie

:

const setAppCookie = () => firebase.auth().currentUser &&
    firebase.auth().currentUser.getToken().then(token => {
        cookies.set('token', token, {
            domain: window.location.hostname,
            expire: 1 / 24, // One hour
            path: '/',
            secure: true // If served over HTTPS
        });
    });

const unsetAppCookie = () => 
    cookies.remove('token', {
        domain: window.location.hostname,
        path: '/',
    });

// triggered by firebase auth changes, this is where you deal
// with your users authentication in your app
fbAuth.onAuthStateChanged(user => {
    if (!user) {
        // user is logged out
        return;
    } 
    // user is logged in
    setAppCookie();
    // Reset cookie before hour expires 
    // (firebase tokens are short lived, say the docs)
    setInterval(setAppCookie, 3500);
});

[...]

// In the logout code
unsetAppCookie();

:

// Before serving express app, enable cookie parsing
app.use(cookieParser());

// In the code dealing with your requests
const { token } = req.cookies;

if (!token) {
    // renderWithoutUser();
}

//
// If user found in cookie, verify the token and render with logged in store
//
console.log('Verifying token', token);
firebase.auth().verifyIdToken(token)
    .then(decodedToken => {
        const uid = decodedToken.sub;
        console.log('User is authenticated for this request', uid);
        // renderWithUser();
    })
    .catch(err => {
        console.error('WARNING token invalid or user not found', err);
        // renderWithoutUser();
    });
+6

Source: https://habr.com/ru/post/1653099/


All Articles