You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
2.0 KiB
52 lines
2.0 KiB
3 years ago
|
// 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);
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
module.exports = fp(customJwtAuth, { fastify: ">=1.0.0" });
|