npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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:seed

4. 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 user
  • createDriver(driverData) - Create driver with license info
  • createVendor(vendorData) - Create vendor with business info
  • getUserById(id) - Get user by ID
  • updateUser(id, data) - Update user profile
  • blockUser(id) - Block user account
  • deleteUser(id) - Soft delete user
  • getUsers(options) - Get paginated users
  • searchUsers(query) - Search users

AuthService Methods

  • login(credentials) - Authenticate user
  • refreshToken(token) - Refresh access token
  • logout(refreshToken) - Logout single session
  • logoutAll(userId) - Logout all sessions
  • changePassword(userId, passwordData) - Change password
  • forgotPassword(email) - Initiate password reset
  • verifyToken(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 database

Sample Users (After Seeding)

🔧 Configuration

Environment Variables

  • DATABASE_URL - PostgreSQL connection string
  • JWT_ACCESS_SECRET - Secret for access tokens
  • JWT_REFRESH_SECRET - Secret for refresh tokens
  • NODE_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 production

Security 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.