Skip to content

distributedvc/amon

Repository files navigation

@distributed/amon

Code Style npm version
npm downloads Package Phobia Bundle Phobia

Small lib exposing reusable utility methods for JWT authentication, using @node-rs/bcrypt & jsonwebtoken under the hood.

Install

With yarn:

yarn add @distributed/amon

With npm:

npm install @distributed/amon

Usage

Auth

Requirements:

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"

Create password hash

import { createPasswordHash } from '@distributed/amon';

const hashPassword = await createPasswordHash('foo');
// => $2a$10$2M95zVobIQOm9BgNmKh/gu7IkH/LM45ZqsySlUQaFLrqAhppvm5Ei

Password validation

import { isPasswordValid } from '@distributed/amon';

const hashPassword = await createPasswordHash('bar');
const valid = await isPasswordValid('bar', hashPassword);
// => true

Get userId

import { getUserId } from '@distributed/amon';
import fastify from 'fastify';

const app = fastify();

app.get('/', async (request, reply) => {
  const userId = getUserId(request.headers);

  reply.type('application/json').code(200);
  return { userId };
});

Create Authpayload

import { getUserId } from '@distributed/amon';
import fastify from 'fastify';

const app = fastify();

app.get('/', async (request, reply) => {
  type User = { username: 'batman' };

  const userId = getUserId(request.headers);

  const user = await db.findUnique({ where: { id: userId } });
  const authPayload = await createAuthPayload<User>(userId, user);

  reply.type('application/json').code(200);
  return authPayload;
});

Create Jwt Token

import { createJwtToken } from '@distributed/amon';

const userId = 'foo';

// JWT Signing options
const options = {};

// App Secret, if process.env.APP_SECREt is not set
const appSecret = 'bar';

const token = await createJwtToken({ userId, options, appSecret });

Development

  1. Install dependencies using yarn install or npm install
  2. Start development server using yarn watch

About

Small library exposing reusable utility methods for JWT auth

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published