Here is an example of how I have implemented it several times, I hope it will be helpful, but the documentation on the internet is very good;)
./ local.js
Here I implement the local authentication, in a separate file if you want to use other strategies, export a getStrategy that is what you use:
const passportLocal = require("passport-local");
function authenticateLocal(username, password, cb) {
User.getById(username, (err, rec) => {
if (err) {
return cb(err);
}
if (rec === null) {
return cb(null, false, { message: "User doesn't exist" });
}
if (!rec.verifyPasswordSync(password)) {
return cb(null, false, { message: "Incorrect password" });
}
cb(null, { username, role: rec.role });
});
}
function getStrategy() {
return new passportLocal.Strategy(authenticateLocal);
}
exports.getStrategy = getStrategy;
passport.js
Here I load the strategies and export a function that uses to load passport
const passport = require("passport");
const local = require("./local");
function serialize(user, cb) {
cb(null, user.username);
}
function deserialize(username, cb) {
User.getById(username, (err, user) => {
if (user) {
cb(null, user);
} else {
cb(null, { username, role: "user" });
}
});
}
function configPassport(config) {
passport.serializeUser(serialize);
passport.deserializeUser(deserialize);
passport.use(local.getStrategy());
}
exports.configPassport = configPassport;
app.js
This is the main module where you create the express router and you nest the middlewares
const passport = require("passport");
const myPassport = require("./passport");
const app = require("express")();
app.use(bodyParser.json({ limit: "5mb" }));
app.use(bodyParser.urlencoded({ extended: false, limit: "5mb" }));
app.use(cookieParser());
app.use(expressSession(expressSessionOptions));
app.use(passport.initialize());
app.use(passport.session());
myPassport.configPassport(config);
module.exports = app;