Files
pos-system/services/iam-service
..
2026-01-07 17:15:25 +07:00

IAM Service

Enterprise-Grade Identity & Access Management Platform

Comprehensive authentication, authorization, identity management, access governance, and compliance reporting for microservices architecture.


At a Glance

Metric Value
API Endpoints 50+ across 10 modules
Database Models 30+ with comprehensive relationships
Authentication Methods 7 (Password, Google, Facebook, GitHub, OIDC, MFA x2)
Authorization Models RBAC + ABAC (Hybrid)
Compliance Frameworks GDPR, SOC2, ISO27001, HIPAA
Caching Layers 3 (Memory → Redis → Database)
Security Features Zero-Trust, Device Fingerprinting, Dynamic Rate Limiting
Production Status Ready (95% implementation)

Features Showcase

🔐 Authentication

  • Email/Password with bcrypt (cost 12)
  • Social Login (Google, Facebook, GitHub)
  • OpenID Connect (Provider + Client)
  • Multi-Factor Authentication (TOTP)
  • JWT + Refresh Tokens (15min/7days)
  • Session Management with Device Tracking
  • CSRF Protection & Secure Cookies

🛡️ Authorization

  • RBAC (Role-Based Access Control)
  • ABAC (Attribute-Based Access Control)
  • Permission Model (resource:action:scope)
  • Direct User Permissions (override roles)
  • Group-Based Permissions
  • Temporary Role Assignments
  • Policy Engine with JSON Logic

👤 Identity Management

  • User Lifecycle Management (CRUD)
  • Extended User Profiles
  • Email/Phone/Document Verification
  • Multi-Tenant Organizations
  • Groups with Hierarchical Structure
  • Bulk User Import/Export
  • User Deactivation & Reactivation

🔍 Access Governance

  • Access Request Workflows
  • Multi-Person Approval Chains
  • Access Reviews & Certification
  • Access Analytics & Reporting
  • Just-In-Time (JIT) Access
  • Temporary Access Grants
  • Anomaly Detection

📊 Compliance & Governance

  • GDPR Compliance Reporting
  • SOC2 Compliance Reporting
  • ISO27001 Compliance Reporting
  • HIPAA Compliance Support
  • Policy Templates & Versioning
  • Risk Scoring & Management
  • Comprehensive Audit Logs

Performance & Security

  • Multi-Layer Caching (L1/L2/L3)
  • Zero-Trust Architecture
  • Device Fingerprinting
  • Dynamic Rate Limiting (by role)
  • Event Sourcing for Audit
  • Connection Pooling
  • Prometheus Metrics & Jaeger Tracing

Quick Start

Get up and running in less than 5 minutes:

Prerequisites

  • Node.js 18+ and pnpm
  • PostgreSQL 14+
  • Redis 6+
  • Docker (optional, for infra)

Installation

# 1. Install dependencies
pnpm install

# 2. Configure environment
cp env.local.example .env.local
# Edit .env.local with your database and Redis URLs

# 3. Setup database
pnpm prisma:generate
pnpm prisma:migrate
pnpm prisma:seed

# 4. Start development server
pnpm dev

Verify Installation

# Health check
curl http://localhost:3001/health

# Expected response:
# {"status":"ok","timestamp":"2024-01-01T00:00:00.000Z"}

First API Call

# Register a new user
curl -X POST http://localhost:3001/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!"
  }'

For detailed setup instructions, see Quick Start Guide.


Documentation

Documentation is organized by audience and use case:

📚 For Developers

Start here if you're integrating with or extending the IAM Service:

Document Description
Getting Started Your first authentication flow
API Reference Complete API documentation (50+ endpoints)
Authentication Guide Password, Social, OIDC, MFA
Authorization Guide RBAC, ABAC, Permission Model
Code Examples TypeScript, React, Vue, Python, cURL

🏗️ For Architects

Understand the system design and data architecture:

Document Description
Architecture Overview System architecture with diagrams
Core Concepts IAM fundamentals explained
Data Model 30+ models with complete ERD
Security Model Security architecture & threat model
IAM Proposal Architectural proposal & roadmap

🚀 For Operators

Deploy and manage the IAM Service in production:

Document Description
Deployment Guide Kubernetes, Docker, Cloud deployment
Configuration Environment variables & settings
Monitoring Metrics, logs, traces, alerts
Troubleshooting Common issues & solutions

🔒 For Security Teams

Audit, compliance, and security features:

Document Description
Security Model Defense-in-depth security
Compliance GDPR, SOC2, ISO27001, HIPAA
Audit Logging Event sourcing & audit trail
Security Skill Security patterns reference

📖 Complete Documentation Index

View all documentation

Core Documentation:

Concepts:

User Guides:

Examples:

Deployment:

Reference:


Architecture Overview

The IAM Service follows a layered architecture with clear separation of concerns:

┌─────────────────────────────────────────────────────────────┐
│                        Client Layer                          │
│              Web Apps │ Mobile Apps │ Services                │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                     Traefik API Gateway                      │
│              Load Balancing │ TLS │ Routing                  │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                      Middleware Stack                        │
│  Correlation ID → Logger → Zero-Trust → Rate Limit →        │
│            Authentication → Authorization                    │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                     Feature Modules (10)                     │
│                                                              │
│  ┌─────────────┐  ┌────────────┐  ┌──────────────┐         │
│  │  Auth       │  │  Identity  │  │  Access      │         │
│  │  Token      │  │  Profile   │  │  Request     │         │
│  │  Session    │  │  Org       │  │  Review      │         │
│  │  RBAC       │  │  Group     │  │  Analytics   │         │
│  │  Social     │  │  Verify    │  │              │         │
│  │  OIDC       │  │            │  │  Governance  │         │
│  │  MFA        │  │            │  │  Compliance  │         │
│  └─────────────┘  └────────────┘  └──────────────┘         │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                      Core Services                           │
│      Cache Service │ Audit Service │ Security Service       │
└─────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────┐
│                        Data Layer                            │
│         PostgreSQL (30+ Models) │ Redis (Cache)             │
└─────────────────────────────────────────────────────────────┘

See ARCHITECTURE.en.md for detailed diagrams and flows.


Key API Endpoints

Authentication (/api/v1/auth)

POST   /register              Register new user
POST   /login                 Login with email/password
POST   /logout                Logout user
POST   /refresh               Refresh access token
POST   /change-password       Change password
GET    /me                    Get current user

Social Authentication (/api/v1/auth/social)

GET    /google                Initiate Google OAuth
GET    /facebook              Initiate Facebook OAuth
GET    /github                Initiate GitHub OAuth
GET    /google/callback       Google OAuth callback
GET    /facebook/callback     Facebook OAuth callback
GET    /github/callback       GitHub OAuth callback

RBAC (/api/v1/rbac)

GET    /roles                 List all roles
POST   /roles                 Create role
GET    /permissions           List all permissions
POST   /users/:id/roles       Assign role to user
DELETE /users/:id/roles/:id   Revoke role from user
POST   /users/:id/permissions Grant permission to user

MFA (/api/v1/mfa)

POST   /totp/enable           Enable TOTP MFA
POST   /totp/verify           Verify TOTP code
POST   /totp/validate         Validate TOTP during login
POST   /totp/disable          Disable TOTP MFA
GET    /devices               List MFA devices

Identity Management (/api/v1/identity)

GET    /users                 List users
POST   /users                 Create user
GET    /users/:id             Get user
PUT    /users/:id             Update user
POST   /users/:id/deactivate  Deactivate user
POST   /users/:id/reactivate  Reactivate user
GET    /users/:id/profile     Get user profile
PUT    /users/:id/profile     Update user profile
POST   /users/:id/avatar      Upload avatar

Access Management (/api/v1/access)

POST   /requests              Create access request
GET    /requests              List access requests
POST   /requests/:id/approve  Approve request
POST   /requests/:id/reject   Reject request
POST   /reviews               Create access review
GET    /reviews               List access reviews
POST   /reviews/:id/items/:id/review  Review access item
GET    /analytics/usage       Get usage analytics

Governance (/api/v1/governance)

POST   /compliance/reports    Create compliance report
GET    /compliance/reports    List compliance reports
POST   /compliance/reports/:id/generate  Generate report
GET    /risk/scores           Get risk scores
POST   /risk/calculate        Calculate user risk
GET    /policies/templates    List policy templates

For complete API documentation, see API Reference.


Database Schema

The IAM Service uses PostgreSQL 14+ with Prisma ORM. Key models:

Core Authentication

  • User - User accounts with email/password/MFA
  • Session - Active user sessions with device tracking
  • RefreshToken - Long-lived refresh tokens with rotation
  • AuthEvent - Audit log for all authentication events
  • SocialAccount - Linked OAuth provider accounts
  • MFADevice - TOTP and WebAuthn devices

Authorization

  • Role - Named collections of permissions (ADMIN, MANAGER, USER)
  • Permission - Granular permissions (resource:action:scope)
  • UserRole - User-role assignments with expiration
  • RolePermission - Role-permission mappings
  • UserPermission - Direct user permissions (override roles)
  • Policy - ABAC policies with JSON Logic conditions

Identity Management

  • Organization - Multi-tenant organizations with hierarchy
  • Group - User groups within organizations
  • GroupMember - Group membership with roles
  • UserProfile - Extended user information
  • IdentityVerification - Email/phone/document verification

Access Management

  • AccessRequest - Access request workflows
  • AccessRequestApprover - Multi-person approval
  • AccessReview - Access certification campaigns
  • AccessReviewItem - Individual review items

Governance

  • ComplianceReport - GDPR, SOC2, ISO27001 reports
  • PolicyTemplate - Reusable policy templates
  • RiskScore - User risk scoring

For complete ERD and schema details, see Data Model.


Security Features

The IAM Service implements defense-in-depth security with multiple layers:

1. Zero-Trust Architecture

  • Every request validated (no implicit trust)
  • Device fingerprinting for session binding
  • Location analysis (IP address validation)
  • Behavioral analysis (unusual patterns)
  • Risk-based authentication decisions

2. Authentication Security

  • Bcrypt password hashing (cost factor 12)
  • JWT tokens with short lifetime (15 minutes)
  • Refresh token rotation with family tracking
  • Secure HTTP-only cookies
  • CSRF protection

3. Authorization Security

  • Principle of least privilege
  • Permission caching (5 minutes TTL)
  • Direct permission overrides
  • Temporary role assignments
  • Group-based inheritance

4. Rate Limiting

  • Dynamic by role:
    • Anonymous: 50 req/15min
    • Regular User: 100 req/15min
    • Moderator: 300 req/15min
    • Admin: 500 req/15min
    • Super Admin: 1000 req/15min
  • Redis-backed distributed limiting
  • Login-specific limits (5 attempts/15min)

5. Audit Logging

  • All authentication events logged
  • All authorization decisions logged
  • Event sourcing for compliance
  • 7-year retention for compliance
  • Correlation IDs for request tracking

6. Input Validation

  • Zod schemas for all inputs
  • SQL injection prevention (Prisma ORM)
  • XSS prevention (Content Security Policy)
  • File upload validation

For complete security details, see Security Model.


Performance

Multi-Layer Caching Strategy

Request → L1 (Memory, 60s) → L2 (Redis, 5-15min) → L3 (PostgreSQL)
  • L1 Cache: In-memory (node-cache), 60s TTL, hot data only
  • L2 Cache: Redis, 5-15min TTL, distributed across instances
  • L3 Cache: PostgreSQL with connection pooling

Cached Data Types

Data Type L1 TTL L2 TTL Invalidation
User Data 60s 15min On user update
Permissions 60s 5min On permission change
User Roles 60s 5min On role assignment
Token Validation N/A Token lifetime On logout
Rate Limit Counters N/A 15min Time-based

Performance Metrics

  • Token Validation: < 1ms (L1 cache hit)
  • Permission Check: < 5ms (L2 cache hit)
  • Login: ~100ms (bcrypt + database + cache)
  • API Response Time: P95 < 100ms

Development

Available Scripts

# Development
pnpm dev              # Start dev server with hot reload

# Building
pnpm build            # Build for production
pnpm start            # Start production server

# Database
pnpm prisma:generate  # Generate Prisma client
pnpm prisma:migrate   # Run migrations
pnpm prisma:seed      # Seed database
pnpm prisma:studio    # Open Prisma Studio

# Testing
pnpm test             # Run tests
pnpm test:watch       # Run tests in watch mode
pnpm test:coverage    # Generate coverage report

# Code Quality
pnpm lint             # Run ESLint
pnpm format           # Format with Prettier
pnpm typecheck        # TypeScript type checking

Project Structure

services/iam-service/
├── src/
│   ├── config/              # Configuration files
│   │   ├── app.config.ts
│   │   ├── database.config.ts
│   │   ├── jwt.config.ts
│   │   └── redis.config.ts
│   ├── core/                # Core utilities
│   │   ├── cache/           # Multi-layer caching
│   │   ├── events/          # Audit logging & event sourcing
│   │   └── security/        # Zero-trust validator
│   ├── modules/             # Feature modules
│   │   ├── auth/            # Core authentication
│   │   ├── rbac/            # RBAC system
│   │   ├── token/           # JWT & Cookie management
│   │   ├── session/         # Session management
│   │   ├── mfa/             # Multi-factor auth
│   │   ├── social/          # Social OAuth
│   │   ├── oidc/            # OpenID Connect
│   │   ├── identity/        # Identity management
│   │   ├── access/          # Access management
│   │   ├── governance/      # Governance & compliance
│   │   ├── feature/         # Feature flags
│   │   ├── health/          # Health checks
│   │   └── metrics/         # Prometheus metrics
│   ├── middlewares/         # Express middlewares
│   ├── repositories/        # Data access layer (Prisma)
│   ├── routes/              # Route definitions
│   ├── types/               # TypeScript types
│   ├── errors/              # Error handling
│   ├── utils/               # Utilities
│   └── docs/                # Swagger documentation
├── prisma/                  # Prisma schema & migrations
│   ├── schema.prisma
│   ├── seed.ts
│   └── migrations/
├── docs/                    # Documentation
├── tests/                   # Tests
└── package.json

Migration from Auth Service

This service was migrated from auth-service to iam-service to reflect its expanded scope as a comprehensive Identity and Access Management platform.

Backward Compatibility

No Breaking Changes: All existing endpoints remain unchanged and fully functional:

  • /api/v1/auth/* - Authentication endpoints
  • /api/v1/rbac/* - RBAC endpoints
  • /api/v1/mfa/* - MFA endpoints
  • /api/v1/sessions/* - Session management endpoints

New Capabilities

The IAM service extends the original auth-service with:

  1. Identity Management:

    • User lifecycle management (CRUD, bulk operations)
    • Extended user profiles with custom fields
    • Email/phone/document verification
    • Multi-tenant organizations with hierarchy
    • Groups with member management
  2. Access Management:

    • Access request workflows with approval chains
    • Access reviews & certification campaigns
    • Access analytics and anomaly detection
    • Just-In-Time (JIT) access
    • Temporary access grants
  3. Governance & Compliance:

    • GDPR compliance reporting
    • SOC2 compliance reporting
    • ISO27001 compliance reporting
    • HIPAA compliance support
    • Policy templates & versioning
    • Risk scoring & management

For detailed migration instructions, see Migration Guide.


Production Deployment

Docker

# Build Docker image
docker build -t goodgo/iam-service:latest .

# Run container
docker run -d \
  --name iam-service \
  -p 3001:3001 \
  -e DATABASE_URL="postgresql://..." \
  -e REDIS_HOST="redis" \
  goodgo/iam-service:latest

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: iam-service
spec:
  replicas: 3
  selector:
    matchLabels:
      app: iam-service
  template:
    metadata:
      labels:
        app: iam-service
    spec:
      containers:
      - name: iam-service
        image: goodgo/iam-service:latest
        ports:
        - containerPort: 3001
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: iam-secrets
              key: database-url
        resources:
          requests:
            cpu: 500m
            memory: 512Mi
          limits:
            cpu: 2000m
            memory: 2Gi
        livenessProbe:
          httpGet:
            path: /health/live
            port: 3001
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /health/ready
            port: 3001
          initialDelaySeconds: 10
          periodSeconds: 5

For complete deployment guides, see Deployment Documentation.


Observability

Metrics (Prometheus)

  • HTTP request duration (histogram)
  • HTTP request count by status code (counter)
  • Active sessions (gauge)
  • Cache hit/miss ratio (counter)
  • Database query duration (histogram)
  • Authentication success/failure rate (counter)

Endpoint: GET /metrics

Logging (Winston)

Structured JSON logs with correlation IDs:

{
  "level": "info",
  "message": "User logged in",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "correlationId": "req-123-456",
  "userId": "user-789",
  "email": "user@example.com",
  "service": "iam-service"
}

Tracing (Jaeger)

Distributed tracing with spans for:

  • HTTP request handling
  • Database queries
  • Cache operations
  • External API calls (OAuth)
  • Authentication flows
  • Authorization checks

Health Checks

# Liveness probe (is the app running?)
curl http://localhost:3001/health/live

# Readiness probe (is the app ready to serve traffic?)
curl http://localhost:3001/health/ready

# Full health check (with dependencies)
curl http://localhost:3001/health

Contributing

This is a proprietary service for the GoodGo platform. For internal development:

  1. Create a feature branch
  2. Make your changes
  3. Write tests
  4. Submit a pull request
  5. Wait for code review

Support


License

Proprietary - GoodGo Platform

© 2024-2026 GoodGo. All rights reserved.



Last Updated: January 2026 Version: 1.0.0 Status: Production Ready