I changed the deserializeuser function to this.
passport.deserializeUser(function (id, done) {
console.log(id + '<- DS')
db.AUTH_USR.findByPk(id, function(err, user){
done(err, user)
})
});
As you can see I’m logging the id just to see it hit the function and it dies console the id I log in with.
Still hanging. Not sure what to do . Below is the complete script
const db = require('./models/index.js');
var express = require('express'),
app = express(),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
bodyParser = require('body-parser'),
session = require('express-session');
const auth_usr_ctrl = require('./controllers/auth_usr_ctrl');
const auth_usr = new auth_usr_ctrl();
// hardcoded users, ideally the users should be stored in a database
//var users = [{"id":111, "username":"amy", "password":"amyspassword"}];
// passport needs ability to serialize and unserialize users out of session
passport.serializeUser(function (user, done) {
console.log(user.user_id + '<- serialize' );
done(null, user.user_id);
});
passport.deserializeUser(function (id, done) {
console.log(id + '<- DS')
db.AUTH_USR.findByPk(id, function(err, user){
done(err, user)
})
});
// passport local strategy for local-login, local refers to this app
passport.use('local-login', new LocalStrategy(
function (username, password, done) {
auth_usr.findOne(username).then(user => {console.log(user); return done(null, user)})
.catch(error => { return done(null, false, {"message" : "No User" })})
})
);
// body-parser for retrieving form data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// initialize passposrt and and session for persistent login sessions
app.use(session({
secret: "tHiSiSasEcRetStr",
resave: true,
saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.sendStatus(401);
}
app.get("/", function (req, res) {
res.send("Hello!");
});
// api endpoints for login, content and logout
app.get("/login", function (req, res) {
res.send("<p>Please login!</p><form method='post' action='/login'><input type='text' name='username'/><input type='password' name='password'/><button type='submit' value='submit'>Submit</buttom></form>");
});
app.post("/login",
passport.authenticate("local-login", { failureRedirect: "/login"}),
function (req, res) {
res.redirect("/content");
});
app.get("/content", isLoggedIn, function (req, res) {
res.send("Congratulations! you've successfully logged in.");
});
app.get("/logout", function (req, res) {
req.logout();
res.send("logout success!");
});
// launch the app
app.listen(3000);
console.log("App running at localhost:3000");