Implemented jwtcount basics
This commit is contained in:
parent
75473cabe7
commit
48cc380504
|
@ -0,0 +1,10 @@
|
|||
|
||||
exports.up = function(knex) {
|
||||
return knex.schema.table('users', function (table) {
|
||||
table.integer("jwtcount").defaultTo(0);
|
||||
});
|
||||
};
|
||||
|
||||
exports.down = function(knex) {
|
||||
|
||||
};
|
|
@ -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) => {
|
||||
|
|
Loading…
Reference in New Issue