diff --git a/migrations/20210818160424_jwtcount.js b/migrations/20210818160424_jwtcount.js new file mode 100644 index 0000000..a117c53 --- /dev/null +++ b/migrations/20210818160424_jwtcount.js @@ -0,0 +1,10 @@ + +exports.up = function(knex) { + return knex.schema.table('users', function (table) { + table.integer("jwtcount").defaultTo(0); + }); +}; + +exports.down = function(knex) { + +}; \ No newline at end of file diff --git a/src/server.js b/src/server.js index 709f7f2..b03c5a1 100644 --- a/src/server.js +++ b/src/server.js @@ -32,23 +32,34 @@ fastify.register(require('fastify-cors'), { preflightContinue: true }) -fastify.decorate('verifyJWT', function (request, reply, done) { +fastify.decorate('verifyJWT', function async (request, reply, done) { let token = request.headers.authorization; - if(!token || token == "" || token == "Bearer"){ + if (!token || token == "" || token == "Bearer") { throw new Error("No jwt provided"); } - if(token.startsWith("Bearer")){ - token=token.replace("Bearer ",""); + if (token.startsWith("Bearer")) { + token = token.replace("Bearer ", ""); fastify.log.info("Detected bearer and replaced it") } - fastify.jwt.verify(token, (err, decoded) => { + fastify.jwt.verify(token, async (err, decoded) => { if (err) { fastify.log.error(err) 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() }) @@ -303,12 +314,17 @@ fastify.after(() => { 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 = { - user: req.user + user: req.user, + jwtcount }; 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) => {