Small lib exposing reusable utility methods for JWT authentication, using
@node-rs/bcrypt&jsonwebtokenunder the hood.
With yarn:
yarn add @distributed/amonWith npm:
npm install @distributed/amonRequirements:
Use process.env.APP_SECRET or pass the appSecret into createAuthPayload / createJwtToken functions.
You can execute the following command to generate your secret:
node -e "console.log(crypto.randomBytes(32).toString('hex'))"# .env
APP_SECRET="45e05712755026248ef0f8f9881182b2cc3db28e64fcc42fb19d3209f5f0d19c"import{createPasswordHash}from'@distributed/amon';consthashPassword=awaitcreatePasswordHash('foo');// => $2a$10$2M95zVobIQOm9BgNmKh/gu7IkH/LM45ZqsySlUQaFLrqAhppvm5Eiimport{isPasswordValid}from'@distributed/amon';consthashPassword=awaitcreatePasswordHash('bar');constvalid=awaitisPasswordValid('bar',hashPassword);// => trueimport{getUserId}from'@distributed/amon';importfastifyfrom'fastify';constapp=fastify();app.get('/',async(request,reply)=>{constuserId=getUserId(request.headers);reply.type('application/json').code(200);return{ userId };});import{getUserId}from'@distributed/amon';importfastifyfrom'fastify';constapp=fastify();app.get('/',async(request,reply)=>{typeUser={username: 'batman'};constuserId=getUserId(request.headers);constuser=awaitdb.findUnique({where: {id: userId}});constauthPayload=awaitcreateAuthPayload<User>(userId,user);reply.type('application/json').code(200);returnauthPayload;});import{createJwtToken}from'@distributed/amon';constuserId='foo';// JWT Signing optionsconstoptions={};// App Secret, if process.env.APP_SECREt is not setconstappSecret='bar';consttoken=awaitcreateJwtToken({ userId, options, appSecret });- Install dependencies using
yarn installornpm install - Start development server using
yarn watch