@wikiccu/nest-auth
Version:
A comprehensive authentication package for NestJS applications with Prisma and PostgreSQL
468 lines (360 loc) โข 13.7 kB
Markdown
# @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
```bash
npm install @wikiccu/nest-auth
```
## Prerequisites
This package requires the following dependencies in your NestJS application:
```bash
npm install @nestjs/common @nestjs/core @nestjs/jwt @nestjs/passport @nestjs/config @nestjs/swagger @prisma/client prisma passport passport-jwt passport-local bcryptjs class-validator class-transformer nodemailer rxjs
```
**Note:** This package is compatible with NestJS v11+ and uses the latest versions of all dependencies. It will automatically work with fresh NestJS installations without version conflicts.
## Quick Start
### 1. Database Setup
First, set up your PostgreSQL database and run the Prisma migrations:
```bash
# Copy the Prisma schema to your project
cp node_modules/@wikiccu/nest-auth/dist/prisma/schema.prisma ./prisma/
# Generate Prisma client
npx prisma generate
# Run migrations
npx prisma migrate dev --name init-auth
```
### 2. Environment Variables
Add the following environment variables to your `.env` file:
```env
# 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:
```typescript
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:
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
// JWT settings
JWT_SECRET="your-secret-key"
JWT_EXPIRES_IN="15m"
REFRESH_TOKEN_EXPIRES_IN="7d"
REFRESH_TOKEN_EXPIRES_IN_REMEMBER="30d"
```
### Email Configuration
```typescript
// 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
```typescript
// 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:
```typescript
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:
```typescript
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 data
- `401 Unauthorized` - Authentication required or invalid credentials
- `403 Forbidden` - Insufficient permissions
- `409 Conflict` - Resource already exists
- `500 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:
```bash
npm test
```
## Postman Collection
A complete Postman collection is included with the package to help you test all authentication endpoints. The collection includes:
### Features
- **All API Endpoints** - Complete coverage of all authentication endpoints
- **Request Examples** - Pre-filled request bodies with example data
- **Response Examples** - Sample responses for each endpoint
- **Environment Variables** - Automatic token management
- **Authentication Flow** - Login/logout flow with automatic token handling
- **Organized Structure** - Endpoints grouped by functionality (Public, Authenticated, Admin)
### Import Instructions
1. **Export the Collection**: Run the export script to copy the collection to your project:
```bash
npm run export-postman
```
Or manually copy the `postman-collection.json` file from the package to your project directory.
2. **Import to Postman**:
- Open Postman
- Click "Import" button
- Select the `postman-collection.json` file
- The collection will be imported with all endpoints and examples
### Environment Setup
1. **Set Base URL**: Update the `baseUrl` variable in the collection to match your API server
2. **Authentication Flow**:
- Run the "Login User" request first
- The collection will automatically store your access and refresh tokens
- All subsequent authenticated requests will use the stored tokens
- Use "Refresh Token" to get new tokens when needed
### Endpoint Groups
- **Public Endpoints**: Registration, login, password reset, email verification
- **Authenticated Endpoints**: Profile management, password change, logout
- **Admin Endpoints**: User management (requires admin role)
### Usage Tips
- Start with "Register User" to create a test account
- Use "Login User" to get authentication tokens
- Test authenticated endpoints with the stored tokens
- Use "Refresh Token" when tokens expire
- Admin endpoints require a user with admin role
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. 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
### v2.0.2
- **NEW:** Added comprehensive Postman collection with all API endpoints
- **NEW:** Included request/response examples for all authentication endpoints
- **NEW:** Added automatic token management and authentication flow
- **NEW:** Created export script (`npm run export-postman`) for easy collection setup
- **NEW:** Enhanced API documentation with detailed endpoint specifications
- **NEW:** Added organized endpoint groups (Public, Authenticated, Admin)
- **IMPROVED:** Better developer experience with ready-to-use API testing tools
### v2.0.1
- **FIX:** Corrected Prisma schema path in README.md from `prisma/schema.prisma` to `dist/prisma/schema.prisma`
- Fixed documentation to match actual package structure
### v2.0.0
- **BREAKING CHANGE:** Updated peer dependencies to use `>=` version ranges for maximum compatibility
- **BREAKING CHANGE:** Removed specific version pinning to allow latest versions
- Fixed dependency conflicts with fresh NestJS installations
- Updated to be compatible with latest NestJS v11+ and all dependencies
- Package now works seamlessly with `npm install` without version conflicts
- Enhanced compatibility with the latest NestJS ecosystem
### v1.0.4
- **BREAKING CHANGE:** Upgraded @nestjs/swagger to v8.0.0 for NestJS v11 compatibility
- Fixed dependency conflict with @nestjs/swagger v7.x (only supports NestJS v9/v10)
- Updated all dependencies to latest stable versions
- Enhanced compatibility with latest NestJS ecosystem
### v1.0.3
- **BREAKING CHANGE:** Upgraded @nestjs/config to v4.0.0 compatibility
- Fixed dependency conflict with @nestjs/config v4.x
- Updated all dependencies to latest stable versions
- Enhanced compatibility with latest NestJS ecosystem
### 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