@gauravsharmacode/user-core
v1.0.11
Published
Core Package for user service - Business logic, database access, and services
Readme
@gauravsharmacode/user-core
Business logic layer for the User Service. This package contains services, utilities, and business rules for user management and authentication, including JWT handling and password security.
📦 Installation
npm install @gauravsharmacode/user-core🏗️ Architecture
This package provides business logic and depends on the data layers:
user-model (base package)
↓
user-repository (depends on user-model + Prisma)
↓
user-core (depends on user-model + user-repository) ← You are here
↓
user-api (depends on user-core)🔧 Key Features
- ✅ Authentication Services: Login, logout, token management
- ✅ User Management: Registration, profile updates, role management
- ✅ Security: bcrypt password hashing, JWT token handling
- ✅ Business Logic: User validation, role-based operations
- ✅ Type Safety: Full TypeScript support with proper type inference const hashedPassword = await PasswordUtils.hash('password123');
// Generate JWT const token = JwtUtils.generateAccessToken({ userId: 'user123' });
## 🏗️ Structure
src/ ├── services/ # Business logic services │ ├── auth.service.ts │ ├── user.service.ts │ └── index.ts ├── utils/ # Utility functions │ ├── password.util.ts │ ├── jwt.util.ts │ ├── validation.util.ts │ └── index.ts └── index.ts
## 🎯 Key Features
### Authentication Service
- User login with email/password
- JWT token generation and validation
- Refresh token management
- Session management
- Password reset functionality
- Account lockout protection
### User Service
- User registration with role assignment
- Profile management and updates
- Role and status management
- User search and pagination
- Admin operations
- Bulk user operations
### Utility Functions
- Secure password hashing with bcrypt
- JWT token utilities with configurable expiration
- Data validation and sanitization
- Email and phone validation
## 📚 API Reference
### AuthService
```typescript
class AuthService {
// Authentication
login(credentials: LoginDto): Promise<LoginResponseDto>
logout(refreshToken: string): Promise<ServiceResponse<void>>
refreshToken(token: RefreshTokenDto): Promise<RefreshTokenResponseDto>
// Password management
forgotPassword(data: ForgotPasswordDto): Promise<ServiceResponse<void>>
resetPassword(data: ResetPasswordDto): Promise<ServiceResponse<void>>
changePassword(userId: string, data: ChangePasswordDto): Promise<ServiceResponse<void>>
// Session management
validateSession(token: string): Promise<User | null>
revokeAllSessions(userId: string): Promise<ServiceResponse<void>>
}UserService
class UserService {
// User registration
register(userData: CreateUserDto): Promise<ServiceResponse<User>>
registerDriver(data: CreateDriverDto): Promise<ServiceResponse<User>>
registerVendor(data: CreateVendorDto): Promise<ServiceResponse<User>>
registerManager(data: CreateManagerDto): Promise<ServiceResponse<User>>
registerAdmin(data: CreateAdminDto): Promise<ServiceResponse<User>>
// User management
getUserById(id: string): Promise<User | null>
getUserByEmail(email: string): Promise<User | null>
updateUser(id: string, data: UpdateUserDto): Promise<ServiceResponse<User>>
deleteUser(id: string): Promise<ServiceResponse<void>>
// Admin operations
updateUserStatus(id: string, status: UserStatus): Promise<ServiceResponse<User>>
updateUserRole(id: string, role: UserRole): Promise<ServiceResponse<User>>
restoreUser(id: string): Promise<ServiceResponse<User>>
// Bulk operations
getUsers(options: UserSearchOptions): Promise<PaginatedResult<User>>
searchUsers(query: string, options: PaginationOptions): Promise<PaginatedResult<User>>
getUserStats(): Promise<UserStats>
}🔧 Configuration
Environment Variables
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRATION=15m
REFRESH_TOKEN_EXPIRATION=7d
PASSWORD_HASH_ROUNDS=12🚀 Development
npm run build # Build TypeScript
npm run dev # Watch mode for development
npm run clean # Clean build artifacts🔗 Dependencies
Production
- user-model: Shared type definitions
- user-repository: Database access layer
- bcryptjs: Password hashing
- jsonwebtoken: JWT token management
- zod: Runtime validation
- nanoid: ID generation
# Generate Prisma client
npm run db:generate
# Run migrations
npm run db:migrate
# Seed with sample data
npm run db:seed4. Build the Package
npm run build🗄️ Database Setup
PostgreSQL Setup
-- Create database
CREATE DATABASE user_service_db;
-- Create user (optional)
CREATE USER user_service WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE user_service_db TO user_service;Environment Variables
DATABASE_URL="postgresql://user_service:your_password@localhost:5432/user_service_db?schema=public"
JWT_ACCESS_SECRET="your-access-secret"
JWT_REFRESH_SECRET="your-refresh-secret"💻 Usage Examples
User Service
import { UserService, CreateUserDto, UserRole } from 'user-core';
const userService = new UserService();
// Create a new rider
const userData: CreateUserDto = {
email: '[email protected]',
password: 'securePassword123!',
firstName: 'John',
lastName: 'Doe',
role: UserRole.RIDER
};
const result = await userService.createUser(userData);
if (result.success) {
console.log('User created:', result.user);
}
// Get user by ID
const user = await userService.getUserById('user-id');
// Update user
await userService.updateUser('user-id', {
firstName: 'Johnny'
});Auth Service
import { AuthService, LoginDto } from 'user-core';
const authService = new AuthService();
// Login
const loginResult = await authService.login({
email: '[email protected]',
password: 'securePassword123!'
});
if (loginResult.success) {
console.log('Login successful');
console.log('Access Token:', loginResult.tokens?.accessToken);
console.log('Refresh Token:', loginResult.tokens?.refreshToken);
}
// Refresh token
const newTokens = await authService.refreshToken({
refreshToken: 'existing-refresh-token'
});
// Logout
await authService.logout('refresh-token');Repository Usage
import { UserRepository, UserRole, UserStatus } from 'user-core';
const userRepo = new UserRepository();
// Find user with role data
const userWithRole = await userRepo.findByIdWithRole('user-id');
// Get paginated users
const users = await userRepo.findAll({
page: 1,
limit: 10,
role: UserRole.DRIVER,
status: UserStatus.ACTIVE
});
// Search users
const searchResults = await userRepo.search('john', {
page: 1,
limit: 5
});
// Get user statistics
const stats = await userRepo.getStats();🔒 Security Features
Password Security
- bcrypt hashing with configurable salt rounds
- Password strength validation
- Secure password reset flow
JWT Authentication
- Separate access and refresh tokens
- Configurable expiration times
- Session management in database
- Automatic cleanup of expired sessions
Input Validation
- Zod-based schema validation
- SQL injection prevention via Prisma
- Type-safe operations
🎯 API Reference
UserService Methods
createUser(userData)- Create new usercreateDriver(driverData)- Create driver with license infocreateVendor(vendorData)- Create vendor with business infogetUserById(id)- Get user by IDupdateUser(id, data)- Update user profileblockUser(id)- Block user accountdeleteUser(id)- Soft delete usergetUsers(options)- Get paginated userssearchUsers(query)- Search users
AuthService Methods
login(credentials)- Authenticate userrefreshToken(token)- Refresh access tokenlogout(refreshToken)- Logout single sessionlogoutAll(userId)- Logout all sessionschangePassword(userId, passwordData)- Change passwordforgotPassword(email)- Initiate password resetverifyToken(token)- Verify JWT token
🗂️ Database Schema
Users Table
- Basic user information (email, name, phone)
- Role and status management
- Timestamp tracking
- Soft delete support
Role-Specific Tables
- Admin: Permissions and department
- Driver: License, vehicle, location, rating
- Rider: Preferences, payment methods, emergency contact
- Manager: Department, team size, managed regions
- Vendor: Company info, business license, fleet
Supporting Tables
- Sessions: JWT refresh token management
- PasswordResetTokens: Password reset flow
- EmailVerificationTokens: Email verification
🧪 Development
Available Scripts
npm run build # Build TypeScript
npm run dev # Watch mode for development
npm run clean # Clean build artifacts
npm run db:generate # Generate Prisma client
npm run db:migrate # Run database migrations
npm run db:seed # Seed database with sample data
npm run db:studio # Open Prisma Studio
npm run db:reset # Reset databaseSample Users (After Seeding)
- Admin: [email protected] (password: admin123!@#)
- Rider: [email protected] (password: rider123!@#)
- Driver: [email protected] (password: driver123!@#)
- Vendor: [email protected] (password: vendor123!@#)
- Manager: [email protected] (password: manager123!@#)
🔧 Configuration
Environment Variables
DATABASE_URL- PostgreSQL connection stringJWT_ACCESS_SECRET- Secret for access tokensJWT_REFRESH_SECRET- Secret for refresh tokensNODE_ENV- Environment (development/production)BCRYPT_SALT_ROUNDS- Password hashing rounds
JWT Configuration
- Access tokens: 15 minutes expiry
- Refresh tokens: 7 days expiry
- Automatic session cleanup
🚀 Production Deployment
Database Migrations
npm run db:deploy # Run migrations in productionSecurity Checklist
- [ ] Strong JWT secrets (64+ characters)
- [ ] Secure PostgreSQL configuration
- [ ] Rate limiting on authentication endpoints
- [ ] HTTPS only in production
- [ ] Regular session cleanup
🔗 Integration
This package is designed to be used by:
- user-api: HTTP API layer
- Background jobs: User processing tasks
- Other microservices: User data access
The clean architecture ensures that business logic is separated from HTTP concerns and can be easily tested and reused.
