Basic jwt implementation :party:

This commit is contained in:
2021-08-18 15:57:23 +02:00
parent 6420ffb055
commit 75473cabe7
3 changed files with 181 additions and 4 deletions

View File

@@ -9,6 +9,7 @@ let config = {
env: process.env.NODE_ENV || 'development',
recognizeProviders: !(process.env.DISABLE_PROVIDERS === 'true'),
registrationEnabled: (process.env.ENABLE_REGISTER === 'true'),
jwt_secret: process.env.JWT_SECRET || "pleaseneverusethisdefaultsecret",
getBaseUrl() {
if (config.https) {
return `https://${config.domain}`;
@@ -22,12 +23,37 @@ const knex = require('knex')(knexConfiguration);
const authenticate = { realm: 'Short' }
fastify.register(require('fastify-auth'))
fastify.register(require('fastify-basic-auth'), { validate, authenticate });
fastify.register(require('fastify-jwt'), {
secret: config.jwt_secret
});
fastify.register(require('fastify-cors'), {
origin: true,
preflight: true,
preflightContinue: true
})
fastify.decorate('verifyJWT', function (request, reply, done) {
let token = request.headers.authorization;
if(!token || token == "" || token == "Bearer"){
throw new Error("No jwt provided");
}
if(token.startsWith("Bearer")){
token=token.replace("Bearer ","");
fastify.log.info("Detected bearer and replaced it")
}
fastify.jwt.verify(token, (err, decoded) => {
if (err) {
fastify.log.error(err)
throw new Error("JWT Validation failed")
}
fastify.log.info(`Token verified. User is ${decoded.user}`)
done()
})
})
//Automagic Amazn redirects on /a/
fastify.get('/a/:id', async (req, res) => {
res.redirect(302, `https://amazon.de/dp/${req.params.id}`)
@@ -277,6 +303,18 @@ fastify.after(() => {
return urls;
});
fastify.post('/api/auth/login', { onRequest: fastify.auth([fastify.basicAuth]) }, (req, reply) => {
const payload = {
user: req.user
};
const token = fastify.jwt.sign({ payload })
reply.send({ token })
});
fastify.post('/api/auth/check', { onRequest: fastify.auth([fastify.basicAuth, fastify.verifyJWT]) }, (req, reply) => {
return "logged in";
})
});
@@ -343,6 +381,7 @@ async function validate(username, password, req, reply) {
if (!(await argon2.verify(user[0].password, password))) {
return new Error('Wrong credentials');
}
req.user = username;
}
// Run the server!