This is my first time here, so I hope I post this correctly.
I am working with Loopback here, and I am having a problem when I try to redirect to another route. Basically I have two middlewares. The first, checks with Firebase if the user if authenticated and allowed to visit /dashboard. If no, I call the next() middleware and this one redirects back to /login again.
Dashboard.js:
'use strict';
const firebase = require("firebase");
exports.dashboard = (req, res, next) => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
console.log("Before render: "+res.headersSent); // false
res.render("dashboard", {photoUrl: user.photoURL, displayName: user.displayName, email: user.email });
console.log("after render: "+res.headersSent);
} else {
// console.log("on else" );
next()
}
});
};
exports.notLogged = (req, res) => {
console.log("no one logged in");
res.redirect('/login');
};
Route on server.js:
app.get('/dashboard', dashboard.dashboard, dashboard.notLogged);
The middleware on login.js:
exports.login = (req, res) => res.render("login")
And its route:
app.get('/login', login.login);
For example, if I try to access "/dashboard" and I am not logged, the "console.log("no one logged in"); " will be twice on the console, or any other log on the flow. It looks like another request was made, but I can't understand why or how. If I remove the redirect and simply end the response or render a page, the problem does not occur.
Thank you! :)
UPDATE
I am back here and still with no solution. This is driving me crazy.