please help me with passportjs local strategy. When I try loggin, my passport flow is : serialize, Success auth and redirect to '/' where req.user is undefined. In passport flow deserialize is call after every serialize, but in my never. I dont know where is the bug, thanks for help.
Require:
var express = require('express');
var bodyParser = require('body-parser');
var objection = require('objection');
var Model = objection.Model;
var Knex = require('knex');
var bcrypt = require('bcrypt');
var expressValidator = require('express-validator');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var LocalStrategy = require('passport-local').Strategy;
var api = express();
Strategy middleware:
passport.use(new LocalStrategy(
async function (username, password, done) {
var user = await User.findOne(username);
if (!user) {
return done(null, false, {message: 'Incorrect username.'});
}
if (!bcrypt.compareSync(password, user.password)) {
return done(null, false, {message: 'Incorrect password.'});
} else {
return done(null, user);
}
}
));
Serialize an Deserialize method:
passport.serializeUser(function (user, done) {
console.log("serialialize");
done(null,user.id);
});
passport.deserializeUser(async function (id, done) {
console.log("deserialialize");
let user = await User.findById(id);
if (user) {
done(null, user);
}
});
Middlewares:
api.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
api.use(bodyParser.json());
api.use(expressValidator());
api.use(cookieParser()); // required before session.
api.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: false}));
api.use(passport.initialize());
api.use(passport.session());
DB configurations:
var knex = Knex({
client: 'pg',
connection: {
user: 'marossmrek',
password: '12345',
database: 'ita-js'
}
});
Model.knex(knex);
class Base extends Model {
static get tableName() {
return this.name.toLowerCase();
}
static async findById(id) {
return await this.query().where({id: id}).limit(1).first();
}
}
class User extends Base {
static async findOne(username) {
return await this.query().where({username: username}).limit(1).first();
}
}
User login routes:
api.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
console.log('Success auth');
res.redirect('/');
});
api.get('/logout', (req, res) => {
req.logout();
res.end();
});
api.get('/', (req,res)=> {
console.log("After redirect: " +req.user);
res.end();
});
api.listen(5000, () => {
console.log("I listen on port 5000");
});