Implemented jwtcount basics

This commit is contained in:
Nicolai Ort 2021-08-18 16:09:34 +02:00
parent 75473cabe7
commit 48cc380504
Signed by: niggl
GPG Key ID: 13AFA55AF62F269F
2 changed files with 35 additions and 9 deletions

View File

@ -0,0 +1,10 @@
exports.up = function(knex) {
return knex.schema.table('users', function (table) {
table.integer("jwtcount").defaultTo(0);
});
};
exports.down = function(knex) {
};

View File

@ -32,23 +32,34 @@ fastify.register(require('fastify-cors'), {
preflightContinue: true preflightContinue: true
}) })
fastify.decorate('verifyJWT', function (request, reply, done) { fastify.decorate('verifyJWT', function async (request, reply, done) {
let token = request.headers.authorization; let token = request.headers.authorization;
if(!token || token == "" || token == "Bearer"){ if (!token || token == "" || token == "Bearer") {
throw new Error("No jwt provided"); throw new Error("No jwt provided");
} }
if(token.startsWith("Bearer")){ if (token.startsWith("Bearer")) {
token=token.replace("Bearer ",""); token = token.replace("Bearer ", "");
fastify.log.info("Detected bearer and replaced it") fastify.log.info("Detected bearer and replaced it")
} }
fastify.jwt.verify(token, (err, decoded) => { fastify.jwt.verify(token, async (err, decoded) => {
if (err) { if (err) {
fastify.log.error(err) fastify.log.error(err)
throw new Error("JWT Validation failed") throw new Error("JWT Validation failed")
} }
fastify.log.info(`Token verified. User is ${decoded.user}`) fastify.log.info(`Token verified. User is ${decoded.user}`);
jwtcount = (await knex.select('jwtcount')
.from('users')
.where('username', '=', req.user)
.limit(1))[0].jwtcount;
if(decoded.jwtcount > jwtcount){
fastify.log.error("Auth ended at jwtcount")
throw new Error("JWT in no longer valid")
}
fastify.log.info(`JWT count verified`);
done() done()
}) })
@ -303,12 +314,17 @@ fastify.after(() => {
return urls; return urls;
}); });
fastify.post('/api/auth/login', { onRequest: fastify.auth([fastify.basicAuth]) }, (req, reply) => { fastify.post('/api/auth/login', { onRequest: fastify.auth([fastify.basicAuth]) }, async (req, reply) => {
const jwtcount = (await knex.select('jwtcount')
.from('users')
.where('username', '=', req.user)
.limit(1))[0].jwtcount;
const payload = { const payload = {
user: req.user user: req.user,
jwtcount
}; };
const token = fastify.jwt.sign({ payload }) const token = fastify.jwt.sign({ payload })
reply.send({ token }) reply.send({ token });
}); });
fastify.post('/api/auth/check', { onRequest: fastify.auth([fastify.basicAuth, fastify.verifyJWT]) }, (req, reply) => { fastify.post('/api/auth/check', { onRequest: fastify.auth([fastify.basicAuth, fastify.verifyJWT]) }, (req, reply) => {