Passport.js local redirect issue (Express 500 error) - passport.js

I have a form that has two fields username and passwort, I submit it using post request.
The route
app.post('/login', users.login)
If my login function is
login: passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
}),
Then after incorrect login url in address string changes to /login (or redirect addres that is in falureRedict), but there is no form page, but 500 Express error page.
If I use custom auth code like:
login: function(req, res, next){
passport.authenticate('local', function(err, user){
if (err || !user){
res.redirect('/login')
} else {
req.logIn(user, function(err) {
console.log('user logged')
if (err){
res.redirect('/login')
} else {
res.redirect('/')
}
});
}
})(req, res, next)
},
What is the issue with my first variant of the code?

Related

Passport.authenticate successRedirect condition after Google OAuth 2.0 identification

I use this Callback route after Google OAuth 2.0 identification
// Original version working:
// Callback route
router.get( '/google/callback',
passport.authenticate( 'google', {
failureRedirect: '/',
successRedirect: '/dashboard',
}));
I want to redirect the general users to '/dashboard/ but the admin (With email like admin#admin.com ) to '/admin'
I'm trying something like this:
// Callback route
router.get( '/google/callback',
passport.authenticate( 'google', {
failureRedirect: '/',
{
if (req.user.mail === 'admin#admin.com') {
return successRedirect: '/admin';
} else
{
return successRedirect: '/dashboard';
}
}
}));
But I donĀ“t know how to insert the (req, res) after the failureRedirect: '/', line
Also the "return" is needed?
Any help?
Why not use a custom callback as prescribed by the package here.
Implementation:
router.get('/google/callback', (req, res, next) =>
passport.authenticate('google', (err, user, info) => {
if (err) return next(err);
if (!user) return res.redirect('/login');
req.logIn(user, err => {
if (err) return next(err);
if (user.mail === 'admin#admin.com') return res.redirect('/admin');
return res.redirect('/dashboard');
});
})(req, res, next)
);

How to pass last visited url to passport.authenticate - node.js express app

In my application's login route I'm using a passport.authenticate() method:
router.post("/login", passport.authenticate("local",
{
successRedirect: "/",
failureRedirect: "/login"
}), function(req, res){ });
But there is implemented fixed redirect url's only. I would like to pass last visited route address - url to this process, but in this implementation authenticate() method didn't take request and response parameters.
You can get the current url using "req.url" and save into session just before you are redirecting the user to /login
req.session.recentUrl = req.url
res.send()
Now modify /login route to
router.post("/login", passport.authenticate("local",{
successRedirect: req.session.recentUrl,
failureRedirect: "/login"
}), function(req, res){ });
Note : Make sure to clear the req.session.recentUrl after handling appropriately.
edit: req is not defined
you this middleware in you post route.
app.get('/protected', function(req, res, next) {
passport.authenticate('local', function(err, user, profile) {
if (err) { return next(err) }
if (!user) { return res.redirect('/signin') }
res.redirect('/account');
})(req, res, next);
});
This issue is already addressed,more info :https://github.com/jaredhanson/passport/issues/1

run a function instead of redirect to other page (passportjs)

I would like to know how to run a function when passport authenticating fails or succeed, for example
.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login', //I would like to run a function here instead of redirecting
failureFlash: false
})(req, res, next);
})
you need to pass a function instead of the config object.
But make sure that you handle the request properly.
ie:
const login = function (req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
console.log(err);
return res.status(401).json({
message: 'Something is not right',
user: user
});
}
req.login(user, {session: false}, function(err) {
if (err) {
res.send(err);
}
return res.json({user});
});
})(req, res);
};

Redirecting to previous page after authentication using node.js and passport

my authentication is working well but Redirecting to previous page after authentication using node.js and passport is not working
*//this is auth.route.js file*
app.post('/login', passport.authenticate('login',{
successRedirect : '/',
failureRedirect : '/login',
failureFlash : true
}));
*// this is ensureAuthenticated function*
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
else
res.redirect('/login');
}
I found the how to do it.
*//this is auth.route.js file*
app.post('/login', function(req, res, next){
passport.authenticate('login', function(err, user, info){
// This is the default destination upon successful login.
var redirectUrl = '/profile';
if (!user) { return res.redirect('/'); }
if (req.session.redirectUrl) {
redirectUrl = req.session.redirectUrl;
req.session.redirectUrl = null;
}
req.logIn(user, function(err){
if (err) { return next(err); }
});
res.redirect(redirectUrl);
})(req, res, next);
});
*// this is ensureAuthenticated function*
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
req.session.redirectUrl = req.url;
req.flash("warn", "You must be logged in to do that")
res.redirect('/login');
}

how to send json as a response after passport authenticationin node.js

I am trying this git example.
Which works well when I integrated it with my project, but what I want to achieve is to send json as a response to the client/request, instead of successRedirect : '/profile' & failureRedirect : '/signup'.
Is it possible to send a json, or is there some other methods to get the same?
Any help will be appreciated,TU
here I modified my code to send json as a response
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/successjson', // redirect to the secure profile section
failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.get('/successjson', function(req, res) {
res.sendfile('public/index.htm');
});
app.get('/failurejson', function(req, res) {
res.json({ message: 'hello' });
});
You can use passport's authenticate function as route middleware in your express application.
app.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
// Then you can send your json as response.
res.json({message:"Success", username: req.user.username});
});
By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked. If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.
Create new route, e.g.: /jsonSend with res.json in it and make successRedirect: '/jsonSend'. That should do it.
There is an official Custom Callback documentation:
app.get('/login', function(req, res, next) {
passport.authenticate('local', 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); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
https://github.com/passport/www.passportjs.org/blob/master/views/docs/authenticate.md
Use passport as a middleware.
router.get('/auth/callback', passport.authenticate('facebook'),
function(req, res){
if (req.user) { res.send(req.user); }
else { res.send(401); }
});
// process the signup form
app.post('/signup', passport.authenticate('local-signup', {
successRedirect : '/successjson', // redirect to the secure profile section
failureRedirect : '/failurejson', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
app.get('/successjson', function(req, res) {
res.sendfile('public/index.htm');
});
app.get('/failurejson', function(req, res) {
res.json({ message: 'hello' });
});

Resources