findById in passport.deserializeUser returns null after redirect.
TotallWAR opened this issue · 3 comments
When i login first time - its ok. I can login and ctx.isAuthorized is true. After that im doing a redirect to '/personalArea' where into the method i check again ctx.isAuthorized
and here its always false - deserealize method starts, however findById alwaus return null. I think its problems with session, however sessionId is stored and i have documents into my session collection in DB. What can it be?
I have next login method:
exports.login = async(ctx, next) => {
try {
let user = new User(ctx.request.body);
let hashObject = hash.saltHashPassword(user.password);
//сохраняем хэш и соль
user.password = hashObject.passwordHash;
user.provider = 'local';
user.salt = hashObject.salt;
let result = await ctx.login(user);
ctx.state.user = user;
if (ctx.isAuthenticated()) {
ctx.redirect('/personalArea');
} else {
ctx.redirect('/index');
}
} catch (e) {
ctx.throw(500, e.message);
}
};
Next ser and deser methods:
passport.serializeUser((user, done) => {
console.log('ser:', user)
done(null, user);
});
passport.deserializeUser((id, done) => {
(async() => {
try {
const user = await User.findById(id);
console.log("des: user", user);
done(null, user);
} catch (error) {
console.log("error")
done(error);
}
})();
});
Redirect to method:
exports.renderPersonalArea = async(ctx) => {
try {
if (ctx.isAuthenticated()) {
ctx.type = 'html';
var body = await fs.readFileSync('public/views/personalArea.html', 'utf8');
ctx.body = body.replace('{csrfToken}', ctx.csrf);
} else {
ctx.redirect('/index');
}
} catch (e) {
ctx.throw(404, "Not Found");
}
};
my app config is next:
module.exports = (app, csrf) => {
// sessions
const convert = require('koa-convert')
const session = require('koa-generic-session')
const MongoStore = require('koa-generic-session-mongo')
app.keys = ['lala']
// required for passport session
app.use(convert(session({
secret: 'lala',
saveUninitialized: true,
resave: true,
// using store session on MongoDB using express-session + connect
store: new MongoStore({
url: 'mongodb://localhost:27017/investArtquant',
collection: 'sessions'
})
})));
// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
const auth = require('./auth/auth.js')();
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())
// csrf
app.use(csrf.default({
invalidStatusCode: 403,
invalidTokenMessage: 'Invalid CSRF token',
ignoreMethods: ['GET', 'OPTIONS', 'POST'],
ignorePaths: [],
secretLength: 16,
saltRounds: 10
}));
const routes = require('./route.config.js');
//const routeConfig = require('../config/route.config.js')(app, passport);
const router = routes(app, passport);
app.use(router.middleware());
// const serve = require('koa-static');
// //serve files in public folder(css, js etc)
// app.use(serve(__dirname + '/../public'));
var serve = require('koa2-static-files');
app.use(serve.static(__dirname + '/../public'));
};
And in ctx.state i dont have user. HOWEVER I ALWAYS HAVE CSRF THERE. So i think troubles with passport middlware.
Hi,
since you say deserializeUser
is called, lets focus on the following lines
const user = await User.findById(id);
console.log("des: user", user);
What is the value of id
, which is passed to findById
?
Feel free to reopen the issues if you have additional details
Sorry for not replying!
I had a mistake in deserialize method's param. Param 'id' at this method was an object, but not an id, so i couldnt deserealize correctly.