nest-authenticator
v0.0.8
Published
A robust and flexible authentication library for [NestJS](https://nestjs.com/) applications, designed to seamlessly integrate **normal (email/password)**, **magic link**, and **OAuth** authentication methods using [Prisma](https://www.prisma.io/) as the O
Downloads
31
Readme
Nest Authenticator
A robust and flexible authentication library for NestJS applications, designed to seamlessly integrate normal (email/password), magic link, and OAuth authentication methods using Prisma as the ORM. This library provides pre-built controllers, services, and a recommended Prisma schema to handle user authentication with minimal setup.
Features
- Normal Authentication: Secure email/password authentication with bcrypt password hashing.
- Magic Link Authentication: Passwordless login via secure, time-limited magic links sent via email.
- OAuth Authentication: Integration with popular OAuth providers (e.g., Google, GitHub) using Passport.js.
- Prisma Integration: Pre-configured Prisma schema and services for database operations.
- Type-Safe: Built with TypeScript for type safety and developer productivity.
- Modular Design: Easily extensible with NestJS dependency injection and modular architecture.
- Swagger Documentation: Auto-generated API documentation with
@nestjs/swagger. - Secure by Default: Implements best practices for security, including JWT, password hashing, and token revocation.
Installation
Install the library and its dependencies using npm:
npm install nest-authenticatorInstall Prisma CLI as a development dependency:
npm install prisma --save-devPrerequisites
- Node.js: Version 18 or higher.
- NestJS: Version 9 or higher.
- Database: A Prisma-supported database (e.g., PostgreSQL, MySQL).
- Environment Variables: Configure a
.envfile with necessary variables (see below). - SMTP Service: For magic link emails (e.g., SendGrid, Resend, or Maildev for development).
- OAUTH Account: For google OAUTH integration
Setup
1. Configure Prisma Schema
The library expects a specific Prisma schema for user and token management. Add the following to your prisma/schema.prisma file:
generator client {
provider = "prisma-client-js"
output = "../generated/prisma"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
name String? @db.VarChar(200)
email String @unique @db.VarChar(100)
role String @default("user")
password String @db.VarChar(200)
active Boolean @default(true)
validationId String? @unique
validation Validation? @relation(fields: [validationId], references: [id])
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
@@map("user")
}
model Validation {
id String @id @default(cuid())
isEmailVerify Boolean @default(false)
isPhoneVerify Boolean @default(false)
user User?
@@map("validation")
}
model AccessAttempt {
id String @id @default(cuid())
ipAddress String? @map("ip_address")
userAgent String? @map("user_agent")
email String? @map("email")
cookie String? @map("cookie")
success Boolean @default(false) @map("success")
createdAt DateTime @default(now()) @map("created_at")
@@map("access_attempt")
}
Run the following commands to migrate the schema and generate the Prisma client:
npx prisma migrate dev --name init
npx prisma generate
2. Configure Environment Variables
Create a .env file in the root of your project with the following variables:
#SECURITY CONFIGURATION
JWT_SECRET="secret"
JWT_RESET_SECRET="secret2"
JWT_MAGIC_LINK_SECRET="secret3"
#CONFIGURATOIN
MAX_LOGIN_ATTEMPTS=100
ENABLE_LOGIN_MAGIC_LINK="yes" # yes or no
ENABLE_LOGIN_OAUTH="yes" # yes or no
ENABLE_LOGIN_BASIC="yes" # yes or no
# EMAIL CONFIGURATION
SMTP_EMAIL="[email protected]"
SMTP_PASSWORD='PASSWORD'
SMTP_PORT=555
SMTP_SERVER="smtp.domain.com"
#OAUTH
GOOGLE_ID="YOUR_ID"
GOOGLE_SECRET="YOUR_SECRET"
GOOGLE_SCOPES="SCOPES_SEPARATED_BY_COMMON"
3. Set Up NestJS Module
Import the NestAuthenticatorModule in your AppModule:
import { Module } from '@nestjs/common';
import { NestAuthenticatorModule } from 'nest-authenticator';
import { PrismaService } from './prisma.service';
@Module({
imports: [
//Link this module with your prisma instance
NestAuthenticatorModule.forRoot({
prismaProvider: {
provide: 'PRISMA_PROVIDER',
useValue: PrismaService.getInstance(),
},
}),
],
providers: [],
})
export class AppModule {}4. Start the Application
Run your NestJS application:
npm run start:dev
Access the Swagger documentation at http://localhost:3000/docs to test the authentication endpoints.
Security Considerations
- Password Hashing: Uses bcrypt with a cost factor of 10 for secure password storage.
- JWT Security: Configure a strong
JWT_SECRETand set appropriate expiration times. - Magic Link: Tokens are time-limited (default: 15 minutes) and stored in the database for verification.
- OAuth: Ensure secure callback URLs and store sensitive credentials in environment variables.
- Rate Limiting: Consider adding rate limiting to prevent brute-force attacks (not included by default).
Contributing
Contributions are welcome! Please submit a pull request or open an issue on the GitHub repository.
License
This project is licensed under the MIT License. See the LICENSE file for details.
