Implemented jwt count validation and update on logout
This commit is contained in:
parent
2b22063a81
commit
558b69eeaa
|
@ -32,10 +32,10 @@ fastify.register(require('fastify-cors'), {
|
|||
preflightContinue: true
|
||||
})
|
||||
|
||||
fastify.decorate('verifyJWT', function async (request, reply, done) {
|
||||
fastify.decorate('verifyJWT', function async(request, reply, done) {
|
||||
let token = request.headers.authorization;
|
||||
if (!token || token == "" || token == "Bearer") {
|
||||
throw new Error("No jwt provided");
|
||||
done(new Error("No jwt provided"));
|
||||
}
|
||||
|
||||
if (token.startsWith("Bearer")) {
|
||||
|
@ -46,18 +46,19 @@ fastify.decorate('verifyJWT', function async (request, reply, done) {
|
|||
fastify.jwt.verify(token, async (err, decoded) => {
|
||||
if (err) {
|
||||
fastify.log.error(err)
|
||||
throw new Error("JWT Validation failed")
|
||||
done(new Error("JWT Validation failed"))
|
||||
}
|
||||
fastify.log.info(`Token verified. User is ${decoded.user}`);
|
||||
fastify.log.info(`Token verified. User is ${decoded.payload.user}`);
|
||||
request.user = decoded.payload.user;
|
||||
|
||||
jwtcount = (await knex.select('jwtcount')
|
||||
const jwtcount = (await knex.select('jwtcount')
|
||||
.from('users')
|
||||
.where('username', '=', req.user)
|
||||
.where('username', '=', decoded.payload.user)
|
||||
.limit(1))[0].jwtcount;
|
||||
|
||||
if(decoded.jwtcount > jwtcount){
|
||||
if (decoded.payload.jwtcount < jwtcount || !decoded.payload.jwtcount) {
|
||||
fastify.log.error("Auth ended at jwtcount")
|
||||
throw new Error("JWT in no longer valid")
|
||||
done(new Error("JWT in no longer valid"))
|
||||
}
|
||||
fastify.log.info(`JWT count verified`);
|
||||
done()
|
||||
|
@ -329,7 +330,22 @@ fastify.after(() => {
|
|||
|
||||
fastify.post('/api/auth/check', { onRequest: fastify.auth([fastify.basicAuth, fastify.verifyJWT]) }, (req, reply) => {
|
||||
return "logged in";
|
||||
})
|
||||
});
|
||||
|
||||
fastify.post('/api/auth/logout', { onRequest: fastify.auth([fastify.basicAuth, fastify.verifyJWT]) }, async (req, reply) => {
|
||||
let jwtcount = (await knex.select('jwtcount')
|
||||
.from('users')
|
||||
.where('username', '=', req.user)
|
||||
.limit(1))[0].jwtcount;
|
||||
jwtcount += 1;
|
||||
await knex('users')
|
||||
.where('username', '=', req.user)
|
||||
.update({
|
||||
jwtcount
|
||||
});
|
||||
|
||||
return "Done!";
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
|
Loading…
Reference in New Issue