Passport authenticate, need basic explanation - node.js

Can someone explain what is and why do we include (req, res, next), at the end of the passport.authenticate, all I've seen so far in tutorials is that we need it because we want it to fire off immediately, but I don't really understand it.
Here is the code:
router.post('/login', (req, res, next) => { <br>
passport.authenticate('local', { <br>
successRedirect: '/songs/list', <br>
failureRedirect: '/users/login', <br>
failureFlash: true <br>
})(req, res, next); <---- *This line*

You are declaring a function and calling it immediately..You do this so you can access the req object inside the passport.authenticate.
So if you need to access the request object inside the passport you need a custom callback.Your code seems not to use the req object, so you simple use
app.post("/protected",passport.authenticate("local",{
successRedirect:"/user",
failureRedirect:"/login"
}),function(req,res){
});
And if you application need access to req object then :
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);
});
More info # https://github.com/jaredhanson/passport/issues/1

Related

Passport Authentication and login redirection

I have two types of user: Admin and Tester.
What I am trying to do: If the user that logs in is an Admin, render 'dashboardA'. If not, render 'dashboard'.
I don't know how to do this and attempted and failed. Below is my code. I'm a novice
Present code
This works fine but it does not differentiate between the userType. I am using handlebars as template engine
const User = require('../models/User');
// Login Handle
router.post('/login', (req, res, next) => {
passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/auth/login',
failureFlash: true
})(req, res, next);
});
This is my failed attempt
// Login Handle
router.post('/login', (req, res, next) => {
passport.authenticate('local', { if(User.userType === 'Admin') {
successRedirect: 'dashboardA',
failureRedirect: '/auth/login',
failureFlash: true
} else {
successRedirect: 'dashboard',
failureRedirect: '/auth/login',
failureFlash: true
}
})(req, res, next);
});
Does any one have ideas on how to successfully go about this?
Thanks in advance!

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

Middleware not populating error when JWT is invalid

I'm using Passport with the passport-jwt strategy to authenticate users with a JavaScript Work Token. I need to be able to authorise users based on some metadata so I've set up a custom callback which I'm attaching to the route.
router.get('/', auth.loginRequired, function (req, res) {...
but I'm having problems calling the function. I've massively simplified it and the strategy as shown below:
module.exports = {
loginRequired: function (req, res, next) {
passport.authenticate('jwt', {session: false}, function(err, user, info) {
if (!err) {
next()
} else {
res.status(401).send
}
})(req, res, next)
}
}
The strategy is shown below:
passport.use(new JwtStrategy(opts, function(payload, done) {
var user = {firstName: 'Geraint', email: 'test.user#test.co.uk'}
if (payload) {
done(null, user)
} else {
done('Error', null)
}
}))
When the JWT is valid, the passport.authenticate callback is being called as expected with null and the user being passed in correctly. When the JWT is invalid though, the error is being passed into the authenticate callback as info. err is null and user is false.
Why are the parameters getting jumbled if there's an error?
I also worked with this and i got the same output. Passport js work in this way only.
You can change condition and it will work
module.exports = {
loginRequired: function (req, res, next) {
passport.authenticate('jwt', {session: false}, function(err, user, info) {
if (user) {
next()
} else {
res.status(401).send
}
})(req, res, next)
}
}
In case of user object present, it will return success otherwise it will return error.
What I do for JWT authentication is:
router.get('/', passport.authenticate('jwt', {session: false}), function (req, res) {...
If the JWT is not valid, then it returns a 401. If it is valid, then it continues into my route.

parameterising passport social login callback

I have the following callbacks for facebook and linkedin callbacks:
router.get('/auth/linkedin/callback', social.linkedin().authenticate('linkedin', {failureRedirect: '/web/login'}), function(req, res, next) { res.redirect(req.session.redirectURL); });
router.get('/auth/facebook/callback', social.facebook().authenticate('facebook', {failureRedirect: '/web/login'}), function(req, res, next) { res.redirect(req.session.redirectURL); });
how do i parameterise them so that i can do away with one liner, say
// somehow get a service from the wildcard in the uri
router.get('/auth/*/callback', social.service().authenticate(service, {failureRedirect: '/web/login'}), function(req, res, next) { res.redirect(req.session.redirectURL); });
Try this one
router.get('/auth/:service/callback', function (req, res, next) {
social[req.params.service]().authenticate(req.params.service, {failureRedirect : '/web/login'})(req, res, next);
}, function (req, res, next) {
res.redirect(req.session.redirectURL);
});

Resources