mirror of
https://gitlab.com/Alamantus/Readlebee.git
synced 2025-06-22 09:16:39 +02:00
Add sequelize models to fastify object; Validate tokens better
This commit is contained in:
parent
52f603ccc4
commit
d213ce6f75
1 changed files with 21 additions and 4 deletions
|
@ -48,9 +48,25 @@ switch (fastify.siteConfig.db_engine) {
|
||||||
fastify.register(require('fastify-sequelize'), sequelizeConfig);
|
fastify.register(require('fastify-sequelize'), sequelizeConfig);
|
||||||
|
|
||||||
// Every request, check to see if a valid token exists
|
// Every request, check to see if a valid token exists
|
||||||
fastify.addHook('onRequest', (request, reply, done) => {
|
fastify.addHook('onRequest', async (request, reply) => {
|
||||||
request.isLoggedInUser = typeof request.cookies.token !== 'undefined' && fastify.jwt.verify(request.cookies.token);
|
request.isLoggedInUser = false;
|
||||||
done();
|
if (typeof request.cookies.token !== 'undefined' && fastify.jwt.verify(request.cookies.token)) {
|
||||||
|
const { id } = fastify.jwt.verify(request.cookies.token);
|
||||||
|
const user = await fastify.models.User.findByPk(id).catch(ex => fastify.log(ex));
|
||||||
|
if (!user) {
|
||||||
|
console.log('Invalid user id from token');
|
||||||
|
request.clearCookie('token', token, {
|
||||||
|
path: '/',
|
||||||
|
expires: new Date(Date.now() - 9999),
|
||||||
|
maxAge: new Date(Date.now() - 9999), // Both are set as a "just in case"
|
||||||
|
httpOnly: true, // Prevents JavaScript on the front end from grabbing it
|
||||||
|
sameSite: true, // Prevents the cookie from being used outside of this site
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
request.isLoggedInUser = true;
|
||||||
|
request.user = user;
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
@ -66,5 +82,6 @@ fastify.listen(fastify.siteConfig.port, function (err, address) {
|
||||||
fastify.log.error(err);
|
fastify.log.error(err);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
fastify.log.info(`server listening on ${address}`);
|
|
||||||
|
fastify.decorate('models', require('./getSequelizeModels')(fastify.sequelize));
|
||||||
});
|
});
|
Loading…
Add table
Reference in a new issue