Small lib exposing reusable utility methods for JWT authentication, using
@node-rs/bcrypt
&jsonwebtoken
under the hood.
With yarn:
yarn add @distributed/amon
With npm:
npm install @distributed/amon
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"
import { createPasswordHash } from '@distributed/amon';
const hashPassword = await createPasswordHash('foo');
// => $2a$10$2M95zVobIQOm9BgNmKh/gu7IkH/LM45ZqsySlUQaFLrqAhppvm5Ei
import { isPasswordValid } from '@distributed/amon';
const hashPassword = await createPasswordHash('bar');
const valid = await isPasswordValid('bar', hashPassword);
// => true
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 };
});
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;
});
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 });
- Install dependencies using
yarn install
ornpm install
- Start development server using
yarn watch