@evara-group/guard
v3.0.6
Published
A reusable **authentication and authorization** package for NestJS applications with isolated database support. This package provides a complete auth system with its own dedicated database connection, allowing you to reuse authentication across multiple a
Downloads
1,030
Readme
@evara-group/guard - Authentication & Authorization Package
A reusable authentication and authorization package for NestJS applications with isolated database support. This package provides a complete auth system with its own dedicated database connection, allowing you to reuse authentication across multiple applications while each application maintains its own separate database.
🚀 Features
- ✅ Isolated Database Connection - Dedicated auth database that doesn't conflict with your app's database
- ✅ Role-based access control (
UserRole) - ✅ JWT-based authentication with configurable expiration
- ✅ Built-in
AuthGuardfor route protection - ✅ Built-in
RolesGuardfor role-based authorization - ✅
@Roles()decorator for easy role checking - ✅
@AuthUser()decorator for easy access to authenticated user - ✅ Complete user management (CRUD operations)
- ✅ Password hashing with bcrypt
- ✅ Type-safe with TypeScript and DTOs
📦 Installation
npm install @evara-group/guard
# or
pnpm add @evara-group/guard
# or
yarn add @evara-group/guard🏗️ Architecture
This package uses a named TypeORM connection (AUTH_DATABASE_CONNECTION) to ensure complete isolation from your application's database. This means:
- ✅ Your app can have its own database connection
- ✅ The auth package uses a separate, dedicated database for users
- ✅ No conflicts between connections
- ✅ Easy to reuse across multiple applications
Module Structure
The package follows the same architecture pattern as dms-new-backend-nestjs:
AuthorizationGuardModule- Unified entry point that:- Configures TypeORM connection for the auth database (named connection)
- Loads
UserModule(simple module for user management) - Loads
AuthModule(simple module for authentication)
UserModule- Simple module that:- Uses
TypeOrmModule.forFeature([User], AUTH_DATABASE_CONNECTION) - Provides
UserServicefor CRUD operations - Exports
UserServiceandTypeOrmModule
- Uses
AuthModule- Simple module that:- Imports
UserModuledirectly - Configures JWT using
JwtModule.registerAsync()withConfigService - Provides
AuthServiceandJwtStrategy - Exports
AuthService
- Imports
This architecture ensures:
- ✅ Clear separation of concerns
- ✅ Proper dependency resolution
- ✅ Simple, maintainable code structure
- ✅ Follows NestJS best practices
📖 Usage
1. Basic Setup
In your app.module.ts:
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AuthorizationGuardModule } from "@evara-group/guard";
@Module({
imports: [
// Global configuration
ConfigModule.forRoot({
isGlobal: true,
envFilePath: [".env"],
}),
// Your application database connection (for business entities)
TypeOrmModule.forRootAsync({
// Your app database configuration
// ...
}),
// Authorization Guard Module - Unified module that configures auth database and loads UserModule & AuthModule
AuthorizationGuardModule.forRoot({
database: {
name: process.env.AUTH_DATABASE_NAME || "auth_db",
host: process.env.AUTH_DATABASE_HOST || "localhost",
port: Number(process.env.AUTH_DATABASE_PORT || "5432"),
user: process.env.AUTH_DATABASE_USER || "postgres",
password: process.env.AUTH_DATABASE_PASSWORD || "postgres",
ssl: process.env.AUTH_DATABASE_SSL === "true" || false,
},
jwtSecret: process.env.JWT_SECRET || "your-secret-key",
expiresIn: "7d", // Optional, defaults to '7d'
}),
// Your other modules...
],
})
export class AppModule {}2. Environment Variables
Create a .env file:
# Auth Database Configuration
AUTH_DATABASE_NAME=auth_db
AUTH_DATABASE_HOST=localhost
AUTH_DATABASE_PORT=5432
AUTH_DATABASE_USER=postgres
AUTH_DATABASE_PASSWORD=postgres
AUTH_DATABASE_SSL=false
# JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production3. Protecting Routes
import { Controller, Get } from "@nestjs/common";
import { AuthGuard, RolesGuard, Roles, AuthUser } from "@evara-group/guard";
import { UseGuards } from "@nestjs/common";
import { UserDTO } from "@evara-group/guard";
@Controller("protected")
@UseGuards(AuthGuard, RolesGuard)
export class ProtectedController {
@Get("profile")
@Roles("user", "admin") // Allow both user and admin roles
getProfile(@AuthUser() user: UserDTO) {
return {
message: `Hello ${user.email}`,
user: user,
};
}
@Get("admin-only")
@Roles("admin") // Only admin can access
adminOnly() {
return { message: "Admin area" };
}
}4. Using Auth Service
import { Injectable } from "@nestjs/common";
import { AuthService } from "@evara-group/guard";
@Injectable()
export class MyService {
constructor(private readonly authService: AuthService) {}
async login(email: string, password: string) {
return this.authService.login({ email, password });
}
}5. Using User Service
import { Injectable } from "@nestjs/common";
import { UserService } from "@evara-group/guard";
@Injectable()
export class MyService {
constructor(private readonly userService: UserService) {}
async getUserById(id: number) {
return this.userService.findById(id);
}
async createUser(userData: CreateUserDTO) {
return this.userService.save(userData);
}
}🔐 Database Setup
Create the Auth Database
The package requires a separate PostgreSQL database for authentication. Create it:
CREATE DATABASE auth_db;Run Migrations
The package uses TypeORM entities. You'll need to:
Option 1: Use TypeORM migrations (recommended)
- Generate migration from the
Userentity - Run migrations on your auth database
- Generate migration from the
Option 2: Use synchronize (development only)
- Modify
AuthorizationGuardModule.forRoot()to setsynchronize: truein the TypeORM config (NOT recommended for production)
- Modify
User Entity Schema
The package includes a User entity with the following fields:
id- Primary keyemail- Unique email addresspassword- Hashed passwordusername- Optional usernameactivated- Account activation statusimageUrl- Optional profile image URLrole- User role (enum: UserRole)resetPasswordRequest- Password reset flagcreatedAt,updatedAt,deletedAt- TimestampscreatedBy,updatedBy,deletedBy- Audit fields
🎯 API Reference
AuthorizationGuardModule
AuthorizationGuardModule.forRoot(options: GuardModuleOptions)
Unified module that configures the TypeORM connection for the auth database and loads both UserModule and AuthModule. This is the recommended way to use the package.
Options:
database- Database configuration objectname- Database namehost- Database hostport- Database port (number)user- Database userpassword- Database passwordssl- Enable SSL (optional, boolean)
jwtSecret- JWT secret key (required)expiresIn- Token expiration time (optional, default: '7d')
Architecture:
The module follows the same pattern as dms-new-backend-nestjs:
- Configures TypeORM connection first (with named connection
AUTH_DATABASE_CONNECTION) - Loads
UserModule(simple module that uses the configured TypeORM connection) - Loads
AuthModule(simple module that importsUserModuleand configures JWT)
This ensures proper dependency resolution and follows NestJS best practices.
Guards
AuthGuard
Protects routes requiring authentication. Validates JWT tokens.
RolesGuard
Checks user roles against route requirements. Must be used with @Roles() decorator.
Decorators
@Roles(...roles: string[])
Specifies which roles can access a route.
@AuthUser()
Extracts the authenticated user from the request.
Services
AuthService
login(dto: AuthLoginDTO)- Authenticate user and return JWT tokenvalidateUser(payload: JwtPayload)- Validate user from JWT payload
UserService
findById(id: number)- Find user by IDfindByFields(options)- Find user by custom criteriasave(userDTO, creator?, updatePassword?)- Create or update userupdate(userDTO, updater?)- Update userdelete(userDTO)- Delete userfindAndCount(options)- Find users with pagination
🔄 Multiple Applications Setup
This package is designed to be reused across multiple applications. Each application can:
- Share the same auth database - All apps authenticate against the same user database
- Have separate application databases - Each app has its own business data
Example setup:
Application A (E-commerce)
├── Auth Database (shared) ← Users from @evara-group/guard
└── App Database A ← Products, Orders, etc.
Application B (CMS)
├── Auth Database (shared) ← Users from @evara-group/guard
└── App Database B ← Articles, Pages, etc.Both applications use the same AuthorizationGuardModule.forRoot() configuration pointing to the same auth database, but each has its own application database.
🛠️ Development
Building the Package
pnpm buildRunning Tests
pnpm test📝 Notes
- The package uses a named TypeORM connection (
AUTH_DATABASE_CONNECTION) to avoid conflicts - Never set
synchronize: truein production - Always use strong JWT secrets in production
- The auth database is completely isolated from your application database
- All password operations use bcrypt for security
📄 License
ISC
👤 Author
bassem elsayed
abdullah anter
