My app is on express, mongoDB. I add authorization by session. Don't work logout. There is the link on a page (this is pug):
a(href="/logout") logout
It's handler:
app.get('/logout', function (req, res, next) {
if (req.session) {
// delete session object
req.session.destroy(function (err) {
if (err) {
return next(err);
} else {
return res.redirect('/');
}
});
}
});
When clicked, it displays this and redirect does not occur. If you delete everything except redirect, then redirect will work. But I need to delete the authorization session.
try something like this
app.get('/logout', function (req, res, next) {
// If the user is loggedin
if (req.session.loggedin) {
req.session.loggedin = false;
res.redirect('/');
}else{
// Not logged in
res.redirect('/');
}
});
If you are using passportjs, you need to call the req.logout() to terminate a login session. See documentation here
Related
I have a Node.js Express application and everything works wonderful locally. After deploying the app to Heroku the app runs, but users cannot successfully login. After I click login, the page just reloads and I’m back to the login pop up.
Any ideas where I’m going wrong?
router.get('/login', passport.authenticate('auth0', {
scope: 'openid email profile'
}), function (req, res) {
res.redirect('/');
});
// Perform the final stage of authentication and redirect to previously requested URL or '/user'
router.get('/callback', function (req, res, next) {
passport.authenticate('auth0', function (err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function (err) {
if (err) { return next(err); }
const returnTo = req.session.returnTo;
delete req.session.returnTo;
res.redirect(returnTo || '/');
});
})(req, res, next);
});
I'm building/learning a web-app with React and Express. All of the routes and redirects work but URL won't change and my props won't pass until i manually go to the URL.
For example;
After a successful login (local passport with MongoDB), it renders main page but it's empty since i don't get any data (user id or email etc..) but if enter URL manually or press home button on nav-bar, it works or if i logout it logouts but URL stays at /logout instead of /login. Example code below:
server.js
...
server.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
res.locals.messages = req.flash();
res.locals.user = req.user;
next();
});
server.get("/index", ensureAuthenticated, (req, res) => {
const msg = {name: req.user.name, email: req.user.email};
return app.render(req, res, "/index", msg);
});
server.post("/login", (req, res, next) => {
passport.authenticate("local", function(err, user, info) {
if (err) {
return next(err);
} else if (!user) {
req.flash("error_msg", info.message);
return app.render(req, res, "/login", req.flash());
} else {
req.logIn(user, function(err) {
if (err) {
return next(err);
}
req.user = user.name;
return app.render(req, res, "/index", user.name);
});
}
})(req, res, next);
});
server.get("/logout", (req, res) => {
req.logOut();
req.flash("success_msg", "done!");
return app.render(req, res, "/login", req.flash());
});
server.get("*", ensureAuthenticated, (req, res) => {
return handle(req, res);
});
I think that what you meant by return app.render(req, res, "/index", user.name); on your login method, is actually a redirect.
What render does is take the file and the data you give it and then send it back to the browser as a response.
However, what you're trying to do is have the user go to a different URL if the login process is successful, that can be accomplished by doing the following:
res.redirect('/index')
This will make the server go to your index route, which in turn executes all the code required for your user data to be loaded!
You can learn more about redirect and render by looking at the express docs.
I am trying to set it to true and only then redirect to another page. However I get redirected first and then it's set to true..
Code:
exports.logIn= function(req, res, next) {
req.session.loggedIn = true;
res.redirect("/home");
};
You can achieve this using res.locals
exports.logIn= function(req, res, next) {
//AUTHENTICATE
res.locals.loggedIn = true;
res.redirect("/home");
};
Then on '/home' route you can check the user is logged in or not by reading res.locals.loggedIn
if(res.locals.loggedIn){
// DO SOMETHING
} else {
//REDIRECT TO LOGIN
}
I am stucked with one problem. As you can guess from title , problem is that i am making redirect loop . Simple situation but as a beginner i couldn't solve it . I will provide my code for you to see the problem.
So this is my express routers `
const passport = require('passport');
module.exports = (app) => {
app.get('/auth/eventbrite',
passport.authenticate('eventbrite', {}));
app.get('/auth/eventbrite/callback',
passport.authenticate('eventbrite', { failureRedirect: '/' }),
(req, res) => {
if (!req.user) {
throw new Error('user null');
}
res.redirect('/dashboard');
});
app.get('/api/logout', (req, res) => {
req.session = null;
req.logout();
res.redirect('/');
});
app.get('/api/current_user', (req, res) => {
res.send(req.user);
});
app.get('/dashboard', (req, res) => {
console.log(req.user, 'user');
if (!req.user) {
res.redirect('/');
} else {
res.redirect('/dashboard');
}
});
};
You can notice that i redirect user to /dashboard both in passport authentication and for get requests . My goal is to prevent user to come to dashboard if he/she is not authenticated .
If the user is logged in and is redirected to the dashboard, the dashboard redirects him again to the dashboard. This creates an endless loop. Instead, if the user is logged in, the dashboard route should respond. Most probably you want to send him the dashboard html page.
Currently using node.js, express & passport.js to create a custom website/application.
Having followed several guides, I have a functioning login/logout system with authentication. However, should a user revisit and their session is still active, it doesn't redirect them to the 'dashboard'.
Current root route:
/* GET login page. */
router.get('/',function(req, res) {
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
});
I am making use of the isAuthenticated function, as below:
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
How do I get it to automatically redirect users with an existing session? Any pointers most welcome!
Ok, I figured it out. In the / route, I queried whether req.user was set.
/* GET login page. */
router.get('/',function(req, res) {
if(req.user){
res.redirect("/dashboard");
}else{
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
}
});
You can attach a middleware with "/" endpoint something like this.
router.get('/', sessionValidate, function(req, res, next) {
res.render('login');
});
Where sessionValidate looks something like this :
function sessionValidate(req,res,next){
console.log(req.user,"i am here");
users.findById(req.user,function(err, user) {
if(user!=null){
req.session.user = user;
res.locals.user=user;
res.redirect("/home")
}
else {
next();
}
});
}