// Have custom Auth Tokens based on the user roles/privileges // operatorAuthenticate role is required for all updates , deletes and create calls for non user specific actions. const fastifyJwt = require("fastify-jwt"); const fp = require("fastify-plugin"); async function customJwtAuth(fastify, opts, next) { fastify.register(fastifyJwt, { secret: "asecretthatsverylongandimportedfromanenvfile", }); fastify.decorate("authenticate", async function (request, reply) { try { // to whatever you want, read the token from cookies for example.. // const token = request.headers.authorization // override the request.headers.authorization to prepend with Bearer as fastifiy verify expects token // in the form - "Bearer tokenvalue" let token = request.headers.authorization; // console.log("Received Token is ... \n"); token = "Bearer " + token; // console.log(token); request.headers.authorization = token; // console.log(request.headers.authorization, "hello"); await request.jwtVerify(); } catch (err) { reply.send(err); } }); fastify.decorate("operatorAuthenticate", async function (request, reply) { try { // to whatever you want, read the token from cookies for example.. // override the request.headers.authorization to prepend with Bearer as fastifiy verify expects token // in the form - "Bearer tokenvalue" let token = request.headers.authorization; token = "Bearer " + token; request.headers.authorization = token; decodedtoken = await request.jwtVerify(); console.log("decodedtoken is ************************", decodedtoken); userRoles = decodedtoken.roles; if (userRoles.indexOf("operator") === -1) { reply.send({ error: { message: "You Do not have permission to execute this action", }, }); } } catch (err) { reply.send(err); } }); next() } module.exports = fp(customJwtAuth, { fastify: ">=1.0.0" });