Package Exports
- @wikiccu/nest-auth
- @wikiccu/nest-auth/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@wikiccu/nest-auth) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@wikiccu/nest-auth
A comprehensive authentication package for NestJS applications with Prisma and PostgreSQL. This package provides a complete authentication system with JWT tokens, role-based access control, email verification, password reset, and more.
Features
- ๐ JWT Authentication - Secure token-based authentication
- ๐ฅ User Management - Complete user registration, login, and profile management
- ๐ Refresh Token Rotation - Secure token refresh mechanism
- ๐ง Email Verification - Email verification with customizable templates
- ๐ Password Reset - Secure password reset via email
- ๐ก๏ธ Role-Based Access Control - Fine-grained permissions system
- ๐ Session Management - Track and manage user sessions
- ๐ Rate Limiting - Built-in rate limiting for security
- ๐ Comprehensive API Documentation - Full Swagger/OpenAPI documentation
- ๐งช TypeScript Support - Full TypeScript support with type definitions
Installation
npm install @wikiccu/nest-authPrerequisites
This package requires the following dependencies in your NestJS application:
npm install @nestjs/common@^11.0.0 @nestjs/core@^11.0.0 @nestjs/jwt@^11.0.0 @nestjs/passport@^11.0.0 @nestjs/config@^3.0.0 @prisma/client@^5.0.0 prisma@^5.0.0 passport@^0.7.0 passport-jwt@^4.0.1 passport-local@^1.0.0 bcryptjs@^2.4.3 class-validator@^0.14.0 class-transformer@^0.5.1 nodemailer@^6.9.0 rxjs@^7.8.0Note: This package is compatible with NestJS v11. If you're using an older version, please upgrade your NestJS dependencies first.
Quick Start
1. Database Setup
First, set up your PostgreSQL database and run the Prisma migrations:
# Copy the Prisma schema to your project
cp node_modules/@wikiccu/nest-auth/prisma/schema.prisma ./prisma/
# Generate Prisma client
npx prisma generate
# Run migrations
npx prisma migrate dev --name init-auth2. Environment Variables
Add the following environment variables to your .env file:
# Database
DATABASE_URL="postgresql://username:password@localhost:5432/your_database"
# JWT Configuration
JWT_SECRET="your-super-secret-jwt-key"
JWT_EXPIRES_IN="15m"
REFRESH_TOKEN_EXPIRES_IN="7d"
REFRESH_TOKEN_EXPIRES_IN_REMEMBER="30d"
# Email Configuration
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"
EMAIL_FROM="noreply@yourdomain.com"
EMAIL_FROM_NAME="Your App Name"
# Frontend URL (for email links)
FRONTEND_URL="http://localhost:3000"
# Token Expiration
PASSWORD_RESET_TOKEN_EXPIRES_IN="1h"
EMAIL_VERIFICATION_TOKEN_EXPIRES_IN="24h"
SESSION_EXPIRES_IN="24h"
# Security
BCRYPT_ROUNDS=12
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION="15m"3. Import the Module
Import the AuthModule in your main application module:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AuthModule } from '@wikiccu/nest-auth';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
AuthModule,
],
})
export class AppModule {}4. Set up Global Guards (Optional)
To protect all routes by default, set up global guards:
import { Module } from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { AuthModule, JwtAuthGuard } from '@wikiccu/nest-auth';
@Module({
imports: [AuthModule],
providers: [
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
export class AppModule {}API Endpoints
Public Endpoints
| Method | Endpoint | Description |
|---|---|---|
| POST | /auth/register |
Register a new user |
| POST | /auth/login |
Login user |
| POST | /auth/refresh |
Refresh access token |
| POST | /auth/forgot-password |
Request password reset |
| POST | /auth/reset-password |
Reset password with token |
| POST | /auth/verify-email |
Verify email address |
| POST | /auth/resend-verification |
Resend email verification |
Protected Endpoints
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| POST | /auth/logout |
Logout user | Yes |
| GET | /auth/profile |
Get user profile | Yes |
| PUT | /auth/profile |
Update user profile | Yes |
| PUT | /auth/change-password |
Change password | Yes |
| GET | /auth/users |
Get all users | Admin |
| POST | /auth/users |
Create user | Admin |
| PUT | /auth/users/:id |
Update user | Admin |
| DELETE | /auth/users/:id |
Delete user | Admin |
Usage Examples
Basic Authentication
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard, CurrentUser, AuthUser } from '@wikiccu/nest-auth';
@Controller('protected')
@UseGuards(JwtAuthGuard)
export class ProtectedController {
@Get('profile')
getProfile(@CurrentUser() user: AuthUser) {
return user;
}
}Role-Based Access Control
import { Controller, Get, UseGuards } from '@nestjs/common';
import { JwtAuthGuard, RolesGuard, Roles, CurrentUser, AuthUser } from '@wikiccu/nest-auth';
@Controller('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
export class AdminController {
@Get('dashboard')
@Roles('admin')
getDashboard(@CurrentUser() user: AuthUser) {
return { message: 'Admin dashboard', user };
}
}Permission-Based Access Control
import { Controller, Post, UseGuards } from '@nestjs/common';
import { JwtAuthGuard, PermissionsGuard, Permissions } from '@wikiccu/nest-auth';
@Controller('users')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class UserController {
@Post('create')
@Permissions('user:create')
createUser() {
return { message: 'User created' };
}
}Public Routes
import { Controller, Get } from '@nestjs/common';
import { Public } from '@wikiccu/nest-auth';
@Controller('public')
export class PublicController {
@Get('health')
@Public()
healthCheck() {
return { status: 'ok' };
}
}Database Schema
The package includes a comprehensive Prisma schema with the following models:
- User - User accounts with authentication data
- Role - User roles for access control
- Permission - Fine-grained permissions
- UserRole - Many-to-many relationship between users and roles
- Session - User session tracking
- RefreshToken - JWT refresh tokens
- PasswordResetToken - Password reset tokens
- EmailVerificationToken - Email verification tokens
Email Templates
The package includes customizable email templates for:
- Email verification
- Password reset
- Welcome emails
- Account locked notifications
- Password change notifications
Configuration Options
JWT Configuration
// JWT settings
JWT_SECRET="your-secret-key"
JWT_EXPIRES_IN="15m"
REFRESH_TOKEN_EXPIRES_IN="7d"
REFRESH_TOKEN_EXPIRES_IN_REMEMBER="30d"Email Configuration
// SMTP settings
SMTP_HOST="smtp.gmail.com"
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER="your-email@gmail.com"
SMTP_PASS="your-app-password"
EMAIL_FROM="noreply@yourdomain.com"
EMAIL_FROM_NAME="Your App Name"Security Configuration
// Security settings
BCRYPT_ROUNDS=12
MAX_LOGIN_ATTEMPTS=5
LOCKOUT_DURATION="15m"Customization
Custom Email Templates
You can extend the EmailService to customize email templates:
import { EmailService } from '@wikiccu/nest-auth';
@Injectable()
export class CustomEmailService extends EmailService {
protected getEmailVerificationTemplate(verificationUrl: string): EmailTemplate {
return {
subject: 'Verify Your Email - Custom App',
html: `<div>Your custom template here</div>`,
text: 'Your custom template here',
};
}
}Custom Guards
You can create custom guards by extending the provided ones:
import { Injectable } from '@nestjs/common';
import { JwtAuthGuard } from '@wikiccu/nest-auth';
@Injectable()
export class CustomAuthGuard extends JwtAuthGuard {
// Add your custom logic here
}Error Handling
The package provides comprehensive error handling with appropriate HTTP status codes:
400 Bad Request- Invalid input data401 Unauthorized- Authentication required or invalid credentials403 Forbidden- Insufficient permissions409 Conflict- Resource already exists500 Internal Server Error- Server errors
Security Features
- Password Hashing - Bcrypt with configurable rounds
- JWT Token Security - Secure token generation and validation
- Refresh Token Rotation - Automatic token rotation for security
- Rate Limiting - Built-in rate limiting for authentication endpoints
- Session Management - Track and manage user sessions
- Account Lockout - Automatic account lockout after failed attempts
- Email Verification - Secure email verification process
- Password Reset - Secure password reset via email tokens
Testing
The package includes comprehensive test coverage. To run tests:
npm testContributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
License
MIT License - see LICENSE file for details
Support
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the examples
Changelog
v1.0.2
- BREAKING CHANGE: Upgraded to NestJS v11 compatibility
- Updated all dependencies to latest stable versions
- Fixed dependency conflicts with newer NestJS versions
- Improved TypeScript configuration for better compatibility
- Updated Jest configuration for latest versions
- Enhanced error handling and type safety
v1.0.1
- Bug fixes and improvements
- Enhanced error handling
v1.0.0
- Initial release
- Complete authentication system
- JWT token management
- Role-based access control
- Email verification and password reset
- Comprehensive API documentation