Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fastify-auth-prisma

Package Overview
Dependencies
Maintainers
0
Versions
741
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fastify-auth-prisma

[![Maintainability](https://api.codeclimate.com/v1/badges/6e747003545ffe76ceac/maintainability)](https://codeclimate.com/github/qlaffont/fastify-auth-prisma/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/6e747003545ffe76ceac/test

  • 1.2.444
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Maintainability Test Coverage npm npm Snyk Vulnerabilities for npm package NPM

Fastify-Auth-Prisma

Fastify plugin with Prisma to make simple & secure authentification middleware. Old Owner: @flexper

Usage


pnpm install fastify-auth-prisma unify-fastify prisma @prisma/client

Initialize Prisma and create a similar schema.prisma

model Token {
  id           String @id @unique @default(uuid())
  refreshToken String
  accessToken  String

  owner   User   @relation(fields: [ownerId], references: [id])
  ownerId String

  createdAt DateTime @default(now())
}

model User {
  id            String  @id @unique @default(uuid())

  tokens          Token[]

  createdAt       DateTime         @default(now())
  updatedAt       DateTime         @updatedAt
}

Add your plugin in your fastify server

import fastify from 'fastify';
import { PrismaClient, User } from '@prisma/client';
import unifyFastifyPlugin from 'unify-fastify';
import {fastifyAuthPrismaPlugin} from 'fastify-auth-prisma';

const prisma = new PrismaClient();
const server = fastify();

declare module 'fastify' {
  interface FastifyRequest {
    connectedUser?: User;
  }
}

await server.register(unifyFastifyPlugin);

await server.register(fastifyAuthPrismaPlugin, {
  config: [{url: "/public/*", method: 'GET'}],
  prisma,
  secret: process.env.JWT_ACCESS_SECRET, // Recommanded to use an external variable but you can use any generated string
});

API

fastifyAuthPrismaPlugin

Options

Field NameTypeDescription
config{url: string, method: HttpMethods}[]Specify which urls are allowed without valid token
cookieIsSignedboolean [OPTIONAL]If cookies is used, precise if value is signed
secretstringSecret use for accessToken generation
prismaPrisma Client
userValidation(user: Prisma[User]) => Promise [OPTIONAL]Function to run to add userValidation on request (ex: isBanned / isEmailValidated)

Return

Field NameTypeDescription
connectedUserPrisma["User"]Connected user
isConnectedbooleanReturn if a user is connected

createUserToken(prisma)(userId, {secret, refreshSecret, accessTokenTime, refreshTokenTime})

Options

Field NameTypeDescription
prismaPrisma Client
userIdstring
secretstringSecret use for accessToken generation
refreshSecretstring?Secret use for refreshToken generation
accessTokenTimestringTime validity for accessToken Help for time format
refreshTokenTimestringTime validity for refreshToken Help for time format

Return

Field NameTypeDescription
accessTokenstring
refreshTokenstring

removeUserToken(prisma)(accessToken)

Options

Field NameTypeDescription
prismaPrisma Client
accessTokenstring

Return void

removeAllUserTokens(prisma)(userId)

Options

Field NameTypeDescription
prismaPrisma Client
userIdstring

Return void

refreshUserToken(prisma)(refreshToken, { secret, refreshSecret, accessTokenTime })

Options

Field NameTypeDescription
prismaPrisma Client
refreshTokenstringRefresh token generated
secretstringSecret use for accessToken generation
refreshSecretstringSecret use for refreshToken generation
accessTokenTimestringTime validity for accessToken Help for time format

Return

Field NameTypeDescription
accessTokenstring
refreshTokenstring

getAccessTokenFromRequest(req)

Options

Field NameTypeDescription
reqFastify request

Return string

Config Array

To configure your public routes, you need to specify your url and your method. You can use some alias too :

  • Standard example : {url: '/test/toto', method: 'GET'}
  • Match url who start with test : {url: '/test/*', method: 'GET'}
  • Match all methods for this url : {url: '/test/toto', method: '*'}
  • Match url who contain dynamic variable in it : {url: '/test/:var1/test', method: 'GET'}

You can combine all this options of course ! {url: '/test/:testvar/toto/*', method: '*'}

Test

To test this package, you need to run a PostgresSQL server :


docker-compose up -d
chmod -R 777 docker
pnpm prisma migrate deploy
pnpm test

Maintain

This package use TSdx. Please check documentation to update this package.

FAQs

Package last updated on 16 Jul 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc