Skip to content

Instantly share code, notes, and snippets.

@paigen11
Created September 4, 2018 20:50
Show Gist options
  • Save paigen11/c72c8c20da9cd440f45025a1b05e5e58 to your computer and use it in GitHub Desktop.
Save paigen11/c72c8c20da9cd440f45025a1b05e5e58 to your computer and use it in GitHub Desktop.
Passport local and Passport JWT authentication with custom callbacks examples with a user registration MERN service.
import passport from 'passport';
module.exports = app => {
app.get('/findUser', (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
if (err) {
console.log(err);
}
if (info != undefined) {
console.log(info.message);
res.send(info.message);
} else {
console.log('user found in db from route');
res.status(200).send({
auth: true,
first_name: user.first_name,
last_name: user.last_name,
email: user.email,
username: user.username,
password: user.password,
message: 'user found in db',
});
}
})(req, res, next);
});
};
import User from '../sequelize';
import jwtSecret from '../config/jwtConfig';
import jwt from 'jsonwebtoken';
import passport from 'passport';
module.exports = app => {
app.get('/loginUser', (req, res, next) => {
passport.authenticate('login', (err, user, info) => {
if (err) {
console.log(err);
}
if (info != undefined) {
console.log(info.message);
res.send(info.message);
} else {
req.logIn(user, err => {
User.findOne({
where: {
username: user.username,
},
}).then(user => {
const token = jwt.sign({ id: user.username }, jwtSecret.secret);
res.status(200).send({
auth: true,
token: token,
message: 'user found & logged in',
});
});
});
}
})(req, res, next);
});
};
import jwtSecret from './jwtConfig';
import bcrypt from 'bcrypt';
const BCRYPT_SALT_ROUNDS = 12;
const passport = require('passport'),
localStrategy = require('passport-local').Strategy,
User = require('../sequelize'),
JWTstrategy = require('passport-jwt').Strategy,
ExtractJWT = require('passport-jwt').ExtractJwt;
passport.use(
'register',
new localStrategy(
{
usernameField: 'username',
passwordField: 'password',
session: false,
},
(username, password, done) => {
try {
User.findOne({
where: {
username: username,
},
}).then(user => {
if (user != null) {
console.log('username already taken');
return done(null, false, { message: 'username already taken' });
} else {
bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then(hashedPassword => {
User.create({ username, password: hashedPassword }).then(user => {
console.log('user created');
// note the return needed with passport local - remove this return for passport JWT to work
return done(null, user);
});
});
}
});
} catch (err) {
done(err);
}
},
),
);
passport.use(
'login',
new localStrategy(
{
usernameField: 'username',
passwordField: 'password',
session: false,
},
(username, password, done) => {
try {
User.findOne({
where: {
username: username,
},
}).then(user => {
if (user === null) {
return done(null, false, { message: 'bad username' });
} else {
bcrypt.compare(password, user.password).then(response => {
if (response !== true) {
console.log('passwords do not match');
return done(null, false, { message: 'passwords do not match' });
}
console.log('user found & authenticated');
// note the return needed with passport local - remove this return for passport JWT
return done(null, user);
});
}
});
} catch (err) {
done(err);
}
},
),
);
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
secretOrKey: jwtSecret.secret,
};
passport.use(
'jwt',
new JWTstrategy(opts, (jwt_payload, done) => {
try {
User.findOne({
where: {
username: jwt_payload.id,
},
}).then(user => {
if (user) {
console.log('user found in db in passport');
// note the return removed with passport JWT - add this return for passport local
done(null, user);
} else {
console.log('user not found in db');
done(null, false);
}
});
} catch (err) {
done(err);
}
}),
);
import User from '../sequelize';
import passport from 'passport';
module.exports = app => {
app.post('/registerUser', (req, res, next) => {
passport.authenticate('register', (err, user, info) => {
if (err) {
console.log(err);
}
if (info != undefined) {
console.log(info.message);
res.send(info.message);
} else {
req.logIn(user, err => {
const data = {
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
username: user.username,
};
User.findOne({
where: {
username: data.username,
},
}).then(user => {
user
.update({
first_name: data.first_name,
last_name: data.last_name,
email: data.email,
})
.then(() => {
console.log('user created in db');
res.status(200).send({ message: 'user created' });
});
});
});
}
})(req, res, next);
});
};
@jeghers
Copy link

jeghers commented Jan 31, 2021

Dude, that's creepy. Gentlemen don't do that.

@SamX23
Copy link

SamX23 commented Aug 7, 2021

Is this the best practice to learn ? I need to protect end point and some pages, so I thought to use passport local for pages and JWT for endpoints.

Or I need to look others that using JWT for both pages and endpoints ?

Thanks

@paigen11
Copy link
Author

paigen11 commented Aug 7, 2021

Sure, this is as good a place as any to start implementing your own JWT-protected routes.

This implementation works for both pages and routes - certain pages (like the user info page can only be accessed once a JWT is created and stored in local storage), and certain endpoints to fetch data like user info or password info, etc. can only be reached when a JWT token is passed as part of the payload to the server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment