{"_id":"@awallef/nestjs-iam","_rev":"5-b199fb9e4109f936b8d43266636c6020","name":"@awallef/nestjs-iam","dist-tags":{"latest":"1.2.1"},"versions":{"1.0.0":{"name":"@awallef/nestjs-iam","version":"1.0.0","keywords":["nestjs","iam","identity","access-management","authentication","authorization","typescript"],"author":{"name":"Antoine Wallefire","email":"your-email@example.com"},"license":"MIT","_id":"@awallef/nestjs-iam@1.0.0","maintainers":[{"name":"awallef","email":"antoine.wallef@gmail.com"}],"homepage":"https://github.com/awallef/nestjs-iam#readme","bugs":{"url":"https://github.com/awallef/nestjs-iam/issues"},"dist":{"shasum":"96728934a74518e6662895f7b58a08d527d79372","tarball":"https://registry.npmjs.org/@awallef/nestjs-iam/-/nestjs-iam-1.0.0.tgz","fileCount":111,"integrity":"sha512-CCbknJFnQgouKRdSadFy1UaEDpx7jK1DTW1i/CFj45K+X3rc6q1Dc1m7TRiXa0Eun6OqGjleMTBMHLKL7VAVfg==","signatures":[{"sig":"MEUCIGzWDUIx3c7XK5Zuk0DGt2ewB5tIy/iRZ+ba0w3IJYgRAiEAovitajgivPDkSO2DRZhtOqaiY8JF9IX7btlp25KHs8M=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":140705},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"005d50839b895c5b4c22f44026835ef2aaa2a3f6","scripts":{"lint":"eslint \"src/**/*.ts\" --fix","test":"jest","build":"tsc","format":"prettier --write \"src/**/*.ts\"","test:watch":"jest --watch","build:watch":"tsc --watch","test:coverage":"jest --coverage","prepublishOnly":"npm run build"},"_npmUser":{"name":"awallef","email":"antoine.wallef@gmail.com"},"repository":{"url":"git+https://github.com/awallef/nestjs-iam.git","type":"git"},"_npmVersion":"11.4.2","description":"NestJS Identity and Access Management (IAM) library with comprehensive authentication and authorization features","directories":{},"_nodeVersion":"22.14.0","publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","eslint":"^9.10.0","ts-jest":"^29.2.5","ts-node":"^10.9.2","typeorm":"^0.3.20","prettier":"^3.3.3","typescript":"^5.5.4","@types/jest":"^29.5.12","@types/node":"^22.5.4","@nestjs/core":"^10.4.4","@nestjs/common":"^10.4.4","@nestjs/testing":"^10.4.4","@nestjs/typeorm":"^10.0.2","class-validator":"^0.14.1","reflect-metadata":"^0.2.2","class-transformer":"^0.5.1","@typescript-eslint/parser":"^8.5.0","@typescript-eslint/eslint-plugin":"^8.5.0"},"peerDependencies":{"typeorm":"^0.3.0","@nestjs/core":"^10.0.0","@nestjs/common":"^10.0.0","@nestjs/typeorm":"^10.0.0","class-validator":"^0.14.0","reflect-metadata":"^0.2.0","class-transformer":"^0.5.0"},"_npmOperationalInternal":{"tmp":"tmp/nestjs-iam_1.0.0_1758713709425_0.8106639107730154","host":"s3://npm-registry-packages-npm-production"}},"1.1.0":{"name":"@awallef/nestjs-iam","version":"1.1.0","keywords":["nestjs","iam","identity","access-management","authentication","authorization","typescript"],"author":{"name":"Antoine Wallefire","email":"your-email@example.com"},"license":"MIT","_id":"@awallef/nestjs-iam@1.1.0","maintainers":[{"name":"awallef","email":"antoine.wallef@gmail.com"}],"homepage":"https://github.com/awallef/nestjs-iam#readme","bugs":{"url":"https://github.com/awallef/nestjs-iam/issues"},"bin":{"nestjs-iam-cli":"dist/cli/schema-cli.js"},"dist":{"shasum":"d7d6f14a80a8f900bbb39b05c0d504df060b8e8b","tarball":"https://registry.npmjs.org/@awallef/nestjs-iam/-/nestjs-iam-1.1.0.tgz","fileCount":117,"integrity":"sha512-KYGnWPOVowO4QegSesHBCUvPZzG3Jlbv0etgih7NzXEgDmbT60bqWlNGiFDch7lF8kg1yfbXvqxzLh/f+hh1eg==","signatures":[{"sig":"MEUCICmIpcEEhn19wkeH5Mk/WML5puIjeiARN4J+wpb4zsEGAiEAnbqAIsuU6ythMD+KxkSHmgxYU+xFGUmegHEBKeMXvb4=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":174746},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"005d50839b895c5b4c22f44026835ef2aaa2a3f6","scripts":{"lint":"eslint \"src/**/*.ts\" --fix","test":"jest","build":"tsc","format":"prettier --write \"src/**/*.ts\"","build:cli":"tsc src/cli/schema-cli.ts --outDir dist --target es2020 --module commonjs --esModuleInterop --allowSyntheticDefaultImports","test:watch":"jest --watch","build:watch":"tsc --watch","test:coverage":"jest --coverage","prepublishOnly":"npm run build"},"_npmUser":{"name":"awallef","email":"antoine.wallef@gmail.com"},"repository":{"url":"git+https://github.com/awallef/nestjs-iam.git","type":"git"},"_npmVersion":"11.4.2","description":"NestJS Identity and Access Management (IAM) library with comprehensive authentication and authorization features","directories":{},"_nodeVersion":"22.14.0","dependencies":{"pg":"^8.11.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","eslint":"^9.10.0","ts-jest":"^29.2.5","ts-node":"^10.9.2","typeorm":"^0.3.20","prettier":"^3.3.3","@types/pg":"^8.11.0","typescript":"^5.5.4","@types/jest":"^29.5.12","@types/node":"^22.5.4","@nestjs/core":"^10.4.4","@nestjs/common":"^10.4.4","@nestjs/testing":"^10.4.4","@nestjs/typeorm":"^10.0.2","class-validator":"^0.14.1","reflect-metadata":"^0.2.2","class-transformer":"^0.5.1","@typescript-eslint/parser":"^8.5.0","@typescript-eslint/eslint-plugin":"^8.5.0"},"peerDependencies":{"typeorm":"^0.3.0","@nestjs/core":"^10.0.0","@nestjs/common":"^10.0.0","@nestjs/typeorm":"^10.0.0","class-validator":"^0.14.0","reflect-metadata":"^0.2.0","class-transformer":"^0.5.0"},"_npmOperationalInternal":{"tmp":"tmp/nestjs-iam_1.1.0_1758716495705_0.2816618100315147","host":"s3://npm-registry-packages-npm-production"}},"1.1.1":{"name":"@awallef/nestjs-iam","version":"1.1.1","keywords":["nestjs","iam","identity","access-management","authentication","authorization","typescript"],"author":{"name":"Antoine Wallefire","email":"your-email@example.com"},"license":"MIT","_id":"@awallef/nestjs-iam@1.1.1","maintainers":[{"name":"awallef","email":"antoine.wallef@gmail.com"}],"homepage":"https://github.com/awallef/nestjs-iam#readme","bugs":{"url":"https://github.com/awallef/nestjs-iam/issues"},"bin":{"nestjs-iam-cli":"dist/cli/schema-cli.js"},"dist":{"shasum":"d9c4a5bba16587e7bfe2d836f74380fd9b90f71a","tarball":"https://registry.npmjs.org/@awallef/nestjs-iam/-/nestjs-iam-1.1.1.tgz","fileCount":117,"integrity":"sha512-+KUU7wTtDMM4F1Tx/ffswcf6/Z5DvfToh0KF0ClB3LJcVy4ufAhLQFyBMdlS2A/ucLZBFGrrp/5MqVS70F1Yww==","signatures":[{"sig":"MEQCIFFoKagk5kKoKDjP/lQ5QFKFm8CSWm+4ezufsmNgUYrfAiB7TuGYkpsWaKd/TtXl5FOjH6c9MillBqwwU7Z43pQp2w==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":174746},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"80ed0805b5f808ee02427388d7c44a5887632dad","scripts":{"lint":"eslint \"src/**/*.ts\" --fix","test":"jest","build":"tsc","format":"prettier --write \"src/**/*.ts\"","build:cli":"tsc src/cli/schema-cli.ts --outDir dist --target es2020 --module commonjs --esModuleInterop --allowSyntheticDefaultImports","test:watch":"jest --watch","build:watch":"tsc --watch","test:coverage":"jest --coverage","prepublishOnly":"npm run build"},"_npmUser":{"name":"awallef","email":"antoine.wallef@gmail.com"},"repository":{"url":"git+https://github.com/awallef/nestjs-iam.git","type":"git"},"_npmVersion":"11.4.2","description":"NestJS Identity and Access Management (IAM) library with comprehensive authentication and authorization features","directories":{},"_nodeVersion":"22.14.0","dependencies":{"pg":"^8.11.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","eslint":"^9.10.0","ts-jest":"^29.2.5","ts-node":"^10.9.2","typeorm":"^0.3.20","prettier":"^3.3.3","@types/pg":"^8.11.0","typescript":"^5.5.4","@types/jest":"^29.5.12","@types/node":"^22.5.4","@nestjs/core":"^10.4.4","@nestjs/common":"^10.4.4","@nestjs/testing":"^10.4.4","@nestjs/typeorm":"^10.0.2","class-validator":"^0.14.1","reflect-metadata":"^0.2.2","class-transformer":"^0.5.1","@typescript-eslint/parser":"^8.5.0","@typescript-eslint/eslint-plugin":"^8.5.0"},"peerDependencies":{"typeorm":"^0.3.0","@nestjs/core":"^10.0.0","@nestjs/common":"^10.0.0","@nestjs/typeorm":"^10.0.0","class-validator":"^0.14.0","reflect-metadata":"^0.2.0","class-transformer":"^0.5.0"},"_npmOperationalInternal":{"tmp":"tmp/nestjs-iam_1.1.1_1758717396569_0.6577570138560347","host":"s3://npm-registry-packages-npm-production"}},"1.2.0":{"name":"@awallef/nestjs-iam","version":"1.2.0","keywords":["nestjs","iam","identity","access-management","authentication","authorization","typescript","postgresql","mysql","mariadb","strapi-like"],"author":{"name":"Antoine Wallefire","email":"your-email@example.com"},"license":"MIT","_id":"@awallef/nestjs-iam@1.2.0","maintainers":[{"name":"awallef","email":"antoine.wallef@gmail.com"}],"homepage":"https://github.com/awallef/nestjs-iam#readme","bugs":{"url":"https://github.com/awallef/nestjs-iam/issues"},"bin":{"nestjs-iam-cli":"dist/cli/schema-cli.js"},"dist":{"shasum":"4878f70ec6a71b6ad742dd1716a1e5838c1cd3b2","tarball":"https://registry.npmjs.org/@awallef/nestjs-iam/-/nestjs-iam-1.2.0.tgz","fileCount":118,"integrity":"sha512-4KMOiidtFR8grhK7kPppQTeBn6iWqGvY5LbDqkl1bsBYk/1Xe6Vm7aDSjw8woxJPT9J7xe0zsnkVFsk9tOBsIg==","signatures":[{"sig":"MEQCIF6MCA9QvbWrg1Jg8CfMJS/zdSGIhvC7jlejRV56LM/vAiAQUCMozJMWWa/HjuSXxgVBHz7FWveqjvBCGQGGzB6XUQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":178350},"main":"dist/index.js","types":"dist/index.d.ts","gitHead":"da9c90f65e285ccc189d8e2f9d157c995e24c37e","scripts":{"lint":"eslint \"src/**/*.ts\" --fix","test":"jest","build":"tsc","format":"prettier --write \"src/**/*.ts\"","build:cli":"tsc src/cli/schema-cli.ts --outDir dist --target es2020 --module commonjs --esModuleInterop --allowSyntheticDefaultImports","test:watch":"jest --watch","build:watch":"tsc --watch","test:coverage":"jest --coverage","prepublishOnly":"npm run build"},"_npmUser":{"name":"awallef","email":"antoine.wallef@gmail.com"},"repository":{"url":"git+https://github.com/awallef/nestjs-iam.git","type":"git"},"_npmVersion":"11.4.2","description":"NestJS Identity and Access Management (IAM) library with comprehensive authentication and authorization features. Supports PostgreSQL, MySQL, and MariaDB.","directories":{},"_nodeVersion":"22.14.0","dependencies":{},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","eslint":"^9.10.0","ts-jest":"^29.2.5","ts-node":"^10.9.2","typeorm":"^0.3.20","prettier":"^3.3.3","@types/pg":"^8.11.0","typescript":"^5.5.4","@types/jest":"^29.5.12","@types/node":"^22.5.4","@nestjs/core":"^10.4.4","@nestjs/common":"^10.4.4","@nestjs/testing":"^10.4.4","@nestjs/typeorm":"^10.0.2","class-validator":"^0.14.1","reflect-metadata":"^0.2.2","class-transformer":"^0.5.1","@typescript-eslint/parser":"^8.5.0","@typescript-eslint/eslint-plugin":"^8.5.0"},"peerDependencies":{"pg":"^8.11.0","mysql2":"^3.6.0","typeorm":"^0.3.0","@nestjs/core":"^10.0.0","@nestjs/common":"^10.0.0","@nestjs/typeorm":"^10.0.0","class-validator":"^0.14.0","reflect-metadata":"^0.2.0","class-transformer":"^0.5.0"},"peerDependenciesMeta":{"pg":{"optional":true},"mysql2":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/nestjs-iam_1.2.0_1759345239621_0.41200817337909257","host":"s3://npm-registry-packages-npm-production"}},"1.2.1":{"name":"@awallef/nestjs-iam","version":"1.2.1","description":"NestJS Identity and Access Management (IAM) library with comprehensive authentication and authorization features. Supports PostgreSQL, MySQL, and MariaDB.","main":"dist/index.js","types":"dist/index.d.ts","bin":{"nestjs-iam-cli":"dist/cli/schema-cli.js"},"scripts":{"build":"tsc","build:watch":"tsc --watch","build:cli":"tsc src/cli/schema-cli.ts --outDir dist --target es2020 --module commonjs --esModuleInterop --allowSyntheticDefaultImports","prepublishOnly":"npm run build","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage","lint":"eslint \"src/**/*.ts\" --fix","format":"prettier --write \"src/**/*.ts\""},"keywords":["nestjs","iam","identity","access-management","authentication","authorization","typescript","postgresql","mysql","mariadb","strapi-like"],"author":{"name":"Antoine Wallefire","email":"your-email@example.com"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/awallef/nestjs-iam.git"},"bugs":{"url":"https://github.com/awallef/nestjs-iam/issues"},"homepage":"https://github.com/awallef/nestjs-iam#readme","peerDependencies":{"@nestjs/common":"^10.0.0","@nestjs/core":"^10.0.0","@nestjs/typeorm":"^10.0.0","class-transformer":"^0.5.0","class-validator":"^0.14.0","typeorm":"^0.3.0","reflect-metadata":"^0.2.0","pg":"^8.11.0","mysql2":"^3.6.0"},"peerDependenciesMeta":{"pg":{"optional":true},"mysql2":{"optional":true}},"dependencies":{},"devDependencies":{"@nestjs/common":"^10.4.4","@nestjs/core":"^10.4.4","@nestjs/testing":"^10.4.4","@nestjs/typeorm":"^10.0.2","@types/jest":"^29.5.12","@types/node":"^22.5.4","@types/pg":"^8.11.0","@typescript-eslint/eslint-plugin":"^8.5.0","@typescript-eslint/parser":"^8.5.0","class-transformer":"^0.5.1","class-validator":"^0.14.1","eslint":"^9.10.0","jest":"^29.7.0","prettier":"^3.3.3","reflect-metadata":"^0.2.2","ts-jest":"^29.2.5","ts-node":"^10.9.2","typeorm":"^0.3.20","typescript":"^5.5.4"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"_id":"@awallef/nestjs-iam@1.2.1","gitHead":"e9a42ce0625f4b25682a0619b57572e018b8d085","_nodeVersion":"22.14.0","_npmVersion":"11.4.2","dist":{"integrity":"sha512-36KxBGNtkrSN2v6BDJHx3wX3gaakEfpquqZMnPxv4l5AGIhr0U4hp1n99rPLhRqt1uJennTs1lhCJZ++2sQ15A==","shasum":"400ac806cb007534e1e93d01355096184a2b8e62","tarball":"https://registry.npmjs.org/@awallef/nestjs-iam/-/nestjs-iam-1.2.1.tgz","fileCount":118,"unpackedSize":177839,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIEqNFnTT54h/NQ/FnepGKoIjQvofoOhQWZ1YBMbrHN8GAiEAtxoYsnMZXUZ8ngMKV1j2IbtzYuaJICZsu8fQEQ9oUgE="}]},"_npmUser":{"name":"awallef","email":"antoine.wallef@gmail.com"},"directories":{},"maintainers":[{"name":"awallef","email":"antoine.wallef@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/nestjs-iam_1.2.1_1759346895296_0.8572548722462672"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-24T11:35:09.373Z","modified":"2025-10-01T19:28:15.693Z","1.0.0":"2025-09-24T11:35:09.607Z","1.1.0":"2025-09-24T12:21:35.877Z","1.1.1":"2025-09-24T12:36:36.741Z","1.2.0":"2025-10-01T19:00:39.838Z","1.2.1":"2025-10-01T19:28:15.488Z"},"bugs":{"url":"https://github.com/awallef/nestjs-iam/issues"},"author":{"name":"Antoine Wallefire","email":"your-email@example.com"},"license":"MIT","homepage":"https://github.com/awallef/nestjs-iam#readme","keywords":["nestjs","iam","identity","access-management","authentication","authorization","typescript","postgresql","mysql","mariadb","strapi-like"],"repository":{"type":"git","url":"git+https://github.com/awallef/nestjs-iam.git"},"description":"NestJS Identity and Access Management (IAM) library with comprehensive authentication and authorization features. Supports PostgreSQL, MySQL, and MariaDB.","maintainers":[{"name":"awallef","email":"antoine.wallef@gmail.com"}],"readme":"# @awallef/nestjs-iam\n\nA comprehensive NestJS Identity and Access Management (IAM) library that provides authentication and authorization features for NestJS applications.\n\n## Features\n\n- 🔐 **Authentication Management**: Complete user authentication system\n- 🛡️ **Authorization Controls**: Role-based and permission-based access control\n- 🔗 **External Identity Providers**: Support for external authentication providers\n- 📱 **Account Linking**: Link multiple accounts and identities\n- 🎯 **Decorators**: Easy-to-use decorators for guards and user context\n- 🏗️ **TypeORM Integration**: Built-in entities and database schema\n- �️ **Database CLI**: PostgreSQL schema management utilities\n- �📝 **TypeScript Support**: Full TypeScript support with type definitions\n\n## Installation\n\n```bash\nnpm install @awallef/nestjs-iam\n```\n\n### Database Support\n\nThis package supports multiple databases (like Strapi), letting your host application choose:\n\n#### For PostgreSQL\n```bash\nnpm install pg @types/pg\n```\n\n#### For MySQL\n```bash\nnpm install mysql2\n```\n\n#### For MariaDB\n```bash\nnpm install mysql2\n```\n\n### Peer Dependencies\n\nMake sure you have the following peer dependencies installed:\n\n```bash\nnpm install @nestjs/common @nestjs/core @nestjs/typeorm class-transformer class-validator typeorm reflect-metadata\n```\n\n## Database Setup\n\nThis package works with **PostgreSQL**, **MySQL**, and **MariaDB**. Choose your preferred database:\n\n### PostgreSQL Setup\n1. Install driver: `npm install pg @types/pg`\n2. Use schema: `schema/iam-schema.sql`\n3. Configure TypeORM:\n```typescript\nTypeOrmModule.forRoot({\n  type: 'postgres',\n  host: 'localhost',\n  port: 5432,\n  username: 'postgres',\n  password: 'password',\n  database: 'myapp',\n  entities: [/* your entities */],\n  synchronize: false, // Use schema files instead\n})\n```\n\n### MySQL Setup\n1. Install driver: `npm install mysql2`\n2. Use schema: `schema/iam-schema-mysql.sql`\n3. Configure TypeORM:\n```typescript\nTypeOrmModule.forRoot({\n  type: 'mysql',\n  host: 'localhost',\n  port: 3306,\n  username: 'root',\n  password: 'password',\n  database: 'myapp',\n  entities: [/* your entities */],\n  synchronize: false, // Use schema files instead\n})\n```\n\n### MariaDB Setup\n1. Install driver: `npm install mysql2`\n2. Use schema: `schema/iam-schema-mysql.sql`\n3. Configure TypeORM:\n```typescript\nTypeOrmModule.forRoot({\n  type: 'mariadb',\n  host: 'localhost',\n  port: 3306,\n  username: 'root',\n  password: 'password',\n  database: 'myapp',\n  entities: [/* your entities */],\n  synchronize: false, // Use schema files instead\n})\n```\n\n### Using the CLI Tool (PostgreSQL only)\n\nThe package includes a CLI tool to help you set up the PostgreSQL database schema:\n\n```bash\n# Create IAM tables\nnpx nestjs-iam-cli create --database mydb --username postgres --password mypass\n\n# Create tables in a specific schema\nnpx nestjs-iam-cli create --database mydb --username postgres --password mypass --schema iam\n\n# Drop IAM tables\nnpx nestjs-iam-cli drop --database mydb --username postgres --password mypass\n```\n\n#### CLI Options\n\n- `--host <host>`: Database host (default: localhost)\n- `--port <port>`: Database port (default: 5432)\n- `--database <db>`: Database name (required)\n- `--username <user>`: Database username (required)\n- `--password <pass>`: Database password (required)\n- `--schema <schema>`: Schema name (optional)\n\n### Database Schema\n\nThe CLI creates the following tables:\n\n- **accounts**: Store account information\n- **roles**: Define roles (owner, admin, member, viewer)\n- **account_entity_links**: Link accounts to entities with specific roles\n\n#### Example Schema Usage\n\n```typescript\nimport { EntityAccessGuard } from '@awallef/nestjs-iam';\n\n@Controller('companies')\n@UseGuards(EntityAccessGuard)\nexport class CompaniesController {\n  @Get(':id')\n  @EntityAccess({ entityTable: 'companies', requiredRole: 'viewer' })\n  async getCompany(@Param('id') id: string) {\n    // Only users with 'viewer' role or higher for this company can access\n    return this.companiesService.findOne(id);\n  }\n}\n```\n\n## Quick Start\n\n### 1. Import the IAM Module\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { IamModule } from '@awallef/nestjs-iam';\n\n@Module({\n  imports: [\n    IamModule.forRoot({\n      // Configuration options\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n### 2. Use IAM Components\n\n```typescript\nimport { Controller, Get, UseGuards } from '@nestjs/common';\nimport { AuthGuard, User } from '@awallef/nestjs-iam';\n\n@Controller('protected')\n@UseGuards(AuthGuard)\nexport class ProtectedController {\n  @Get('profile')\n  getProfile(@User() user: any) {\n    return user;\n  }\n}\n```\n\n## Core Components\n\n### Entities\n\n- **UserAccount**: Core user account entity\n- **ExternalIdentity**: External identity provider connections\n- **AccountLink**: Links between different user accounts\n- **IdentityProvider**: Configuration for identity providers\n\n### Controllers\n\n- **UserAccountsController**: User account management\n- **ExternalIdentitiesController**: External identity management\n- **AccountLinksController**: Account linking operations\n- **IdentityProvidersController**: Identity provider configuration\n\n### Services\n\n- **UserAccountsService**: User account business logic\n- **ExternalIdentitiesService**: External identity operations\n- **AccountLinksService**: Account linking logic\n- **IdentityProvidersService**: Identity provider management\n\n### Guards\n\n- **AuthGuard**: Authentication verification\n- **RoleGuard**: Role-based authorization\n- **PermissionGuard**: Permission-based authorization\n- **EntityAccessGuard**: Entity-specific access control with roles\n\n### Decorators\n\n- **@User()**: Inject current user into controller methods\n- **@Auth()**: Authentication and authorization decorator\n- **@Roles()**: Role-based access control\n- **@Permissions()**: Permission-based access control\n- **@EntityAccess()**: Entity-specific access control\n\n## Configuration\n\nThe IAM module can be configured using the `forRoot()` method:\n\n```typescript\nIamModule.forRoot({\n  database: {\n    // TypeORM configuration\n  },\n  jwt: {\n    secret: process.env.JWT_SECRET,\n    expiresIn: '1h',\n  },\n  providers: {\n    // External provider configurations\n  },\n})\n```\n\n## Database Schema\n\nThe library includes both TypeORM entities and a PostgreSQL schema for entity access control:\n\n### TypeORM Entities\n- `user_accounts`\n- `external_identities`\n- `account_links`\n- `identity_providers`\n\n### Entity Access Control Tables (via CLI)\n- `accounts`: Core account information\n- `roles`: Available roles (owner, admin, member, viewer)  \n- `account_entity_links`: Links accounts to specific entities with roles\n\n## CLI Tool\n\nThe package includes a command-line tool for database schema management:\n\n```bash\n# Install globally for easier access\nnpm install -g @awallef/nestjs-iam\n\n# Or use with npx\nnpx nestjs-iam-cli create --help\n```\n\n## API Reference\n\n### DTOs\n\nAll DTOs are available for request/response validation:\n\n- `UserAccountDto`\n- `ExternalIdentityDto`\n- `AccountLinkDto`\n- `IdentityProviderDto`\n\n## Examples\n\n### Basic Authentication\n\n```typescript\nimport { Controller, Post, Body } from '@nestjs/common';\nimport { UserAccountsService } from '@awallef/nestjs-iam';\n\n@Controller('auth')\nexport class AuthController {\n  constructor(private userAccountsService: UserAccountsService) {}\n\n  @Post('login')\n  async login(@Body() loginDto: any) {\n    return this.userAccountsService.authenticate(loginDto);\n  }\n}\n```\n\n### Entity Access Control\n\n```typescript\nimport { Controller, Get, UseGuards, Param } from '@nestjs/common';\nimport { EntityAccessGuard, EntityAccess } from '@awallef/nestjs-iam';\n\n@Controller('companies')\n@UseGuards(EntityAccessGuard)\nexport class CompaniesController {\n  @Get(':id')\n  @EntityAccess({ entityTable: 'companies', requiredRole: 'viewer' })\n  async getCompany(@Param('id') id: string) {\n    // Only users with 'viewer' role or higher for this company can access\n    return this.companiesService.findOne(id);\n  }\n\n  @Put(':id')\n  @EntityAccess({ entityTable: 'companies', requiredRole: 'admin' })\n  async updateCompany(@Param('id') id: string, @Body() updateDto: any) {\n    // Only users with 'admin' role for this company can update\n    return this.companiesService.update(id, updateDto);\n  }\n}\n```\n\n### Database Management\n\n```typescript\n// Programmatic schema management\nimport { IamSchemaCli } from '@awallef/nestjs-iam/cli';\n\nconst cli = new IamSchemaCli({\n  host: 'localhost',\n  port: 5432,\n  database: 'myapp',\n  username: 'postgres',\n  password: 'password'\n});\n\nawait cli.connect();\nawait cli.executeSqlFile(); // Create tables\nawait cli.disconnect();\n```\n\n## Identity Provider Integration & Account Mapping\n\nThe IAM system supports multiple identity providers and allows users to have multiple accounts that can be linked together. This is essential for modern applications where users might sign in with different providers (Google, GitHub, Microsoft, etc.).\n\n### Core Concepts\n\n- **UserAccount**: The primary account entity in your system\n- **ExternalIdentity**: Represents a user's account from an external provider\n- **AccountLink**: Links different accounts belonging to the same user\n- **IdentityProvider**: Configuration for external authentication providers\n\n### Data Model Relationships\n\n```\nUserAccount (1) ←→ (Many) ExternalIdentity\n     ↓\nUserAccount (Many) ←→ (Many) UserAccount [via AccountLink]\n     ↓\nUserAccount (Many) ←→ (Many) Entity [via account_entity_links table]\n```\n\n#### Example Data Structure\n\n```typescript\n// A user with multiple provider accounts\nUserAccount {\n  id: \"user-123\",\n  email: \"john@example.com\",\n  displayName: \"John Doe\",\n  externalIdentities: [\n    {\n      provider: \"google\",\n      externalId: \"google-123456\",\n      email: \"john@gmail.com\",\n      profileData: { /* Google profile */ }\n    },\n    {\n      provider: \"github\", \n      externalId: \"github-789\",\n      email: \"john@users.noreply.github.com\",\n      profileData: { /* GitHub profile */ }\n    }\n  ],\n  linkedAccounts: [\n    {\n      targetAccountId: \"user-456\", // A work account\n      linkType: \"merge\",\n      linkedAt: \"2024-01-15\"\n    }\n  ]\n}\n```\n\n### Setting Up Identity Providers\n\n```typescript\nimport { IdentityProvidersService } from '@awallef/nestjs-iam';\n\n@Injectable()\nexport class AuthSetupService {\n  constructor(\n    private identityProvidersService: IdentityProvidersService,\n  ) {}\n\n  async setupProviders() {\n    // Configure Google OAuth\n    await this.identityProvidersService.create({\n      name: 'google',\n      type: 'oauth2',\n      clientId: process.env.GOOGLE_CLIENT_ID,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET,\n      authorizationUrl: 'https://accounts.google.com/o/oauth2/auth',\n      tokenUrl: 'https://oauth2.googleapis.com/token',\n      userInfoUrl: 'https://www.googleapis.com/oauth2/v2/userinfo',\n      scopes: ['email', 'profile'],\n    });\n\n    // Configure GitHub OAuth\n    await this.identityProvidersService.create({\n      name: 'github',\n      type: 'oauth2',\n      clientId: process.env.GITHUB_CLIENT_ID,\n      clientSecret: process.env.GITHUB_CLIENT_SECRET,\n      authorizationUrl: 'https://github.com/login/oauth/authorize',\n      tokenUrl: 'https://github.com/login/oauth/access_token',\n      userInfoUrl: 'https://api.github.com/user',\n      scopes: ['user:email'],\n    });\n  }\n}\n```\n\n### Creating and Linking User Accounts\n\n#### Scenario 1: New User Signs Up with External Provider\n\n```typescript\nimport { \n  UserAccountsService, \n  ExternalIdentitiesService,\n  AccountLinksService \n} from '@awallef/nestjs-iam';\n\n@Controller('auth')\nexport class AuthController {\n  constructor(\n    private userAccountsService: UserAccountsService,\n    private externalIdentitiesService: ExternalIdentitiesService,\n    private accountLinksService: AccountLinksService,\n  ) {}\n\n  @Post('oauth/callback/:provider')\n  async handleOAuthCallback(\n    @Param('provider') provider: string,\n    @Body() oauthData: { code: string, state?: string },\n  ) {\n    // Exchange code for user info (implement OAuth flow)\n    const userInfo = await this.exchangeCodeForUserInfo(provider, oauthData.code);\n    \n    // Check if external identity already exists\n    let externalIdentity = await this.externalIdentitiesService.findByProviderAndExternalId(\n      provider,\n      userInfo.id,\n    );\n\n    if (!externalIdentity) {\n      // Create new user account\n      const userAccount = await this.userAccountsService.create({\n        email: userInfo.email,\n        displayName: userInfo.name,\n        avatarUrl: userInfo.picture,\n      });\n\n      // Create external identity\n      externalIdentity = await this.externalIdentitiesService.create({\n        userAccountId: userAccount.id,\n        provider: provider,\n        externalId: userInfo.id,\n        email: userInfo.email,\n        displayName: userInfo.name,\n        profileData: userInfo,\n      });\n    }\n\n    return this.generateTokens(externalIdentity.userAccount);\n  }\n}\n```\n\n#### Scenario 2: Existing User Adds Another Provider\n\n```typescript\n@Post('link-account/:provider')\n@UseGuards(AuthGuard)\nasync linkExternalAccount(\n  @Param('provider') provider: string,\n  @Body() oauthData: { code: string },\n  @User() currentUser: UserAccount,\n) {\n  // Exchange code for user info\n  const userInfo = await this.exchangeCodeForUserInfo(provider, oauthData.code);\n  \n  // Check if this external account is already linked to someone else\n  const existingExternalIdentity = await this.externalIdentitiesService.findByProviderAndExternalId(\n    provider,\n    userInfo.id,\n  );\n\n  if (existingExternalIdentity && existingExternalIdentity.userAccountId !== currentUser.id) {\n    // The external account belongs to a different user\n    // Option 1: Merge accounts (advanced scenario)\n    return this.proposeAccountMerge(currentUser, existingExternalIdentity.userAccount);\n    \n    // Option 2: Reject linking\n    // throw new ConflictException('This account is already linked to another user');\n  }\n\n  if (!existingExternalIdentity) {\n    // Create new external identity for current user\n    await this.externalIdentitiesService.create({\n      userAccountId: currentUser.id,\n      provider: provider,\n      externalId: userInfo.id,\n      email: userInfo.email,\n      displayName: userInfo.name,\n      profileData: userInfo,\n    });\n  }\n\n  return { message: 'Account linked successfully' };\n}\n```\n\n#### Scenario 3: Account Merging\n\n```typescript\nasync proposeAccountMerge(\n  currentUser: UserAccount,\n  targetUser: UserAccount,\n): Promise<{ mergeToken: string }> {\n  // Create a temporary merge proposal\n  const mergeProposal = await this.accountLinksService.createMergeProposal({\n    sourceAccountId: currentUser.id,\n    targetAccountId: targetUser.id,\n    expiresAt: new Date(Date.now() + 15 * 60 * 1000), // 15 minutes\n  });\n\n  // Send email to both accounts for confirmation\n  await this.emailService.sendMergeConfirmation(currentUser, targetUser, mergeProposal.token);\n  \n  return { mergeToken: mergeProposal.token };\n}\n\n@Post('confirm-merge')\nasync confirmAccountMerge(@Body() { token, confirmed }: { token: string, confirmed: boolean }) {\n  const mergeProposal = await this.accountLinksService.findMergeProposal(token);\n  \n  if (!mergeProposal || mergeProposal.expiresAt < new Date()) {\n    throw new BadRequestException('Invalid or expired merge token');\n  }\n\n  if (!confirmed) {\n    await this.accountLinksService.deleteMergeProposal(token);\n    return { message: 'Account merge cancelled' };\n  }\n\n  // Perform the merge\n  await this.mergeUserAccounts(mergeProposal.sourceAccountId, mergeProposal.targetAccountId);\n  \n  return { message: 'Accounts merged successfully' };\n}\n\nprivate async mergeUserAccounts(sourceId: string, targetId: string) {\n  // Move all external identities from source to target\n  await this.externalIdentitiesService.transferToAccount(sourceId, targetId);\n  \n  // Move all account links from source to target\n  await this.accountLinksService.transferToAccount(sourceId, targetId);\n  \n  // Move all entity access from source to target\n  await this.accountLinksService.transferEntityAccess(sourceId, targetId);\n  \n  // Soft delete or mark the source account as merged\n  await this.userAccountsService.markAsMerged(sourceId, targetId);\n}\n```\n\n### Retrieving User Accounts and Identities\n\n#### Get All Linked Accounts for a User\n\n```typescript\n@Get('profile/accounts')\n@UseGuards(AuthGuard)\nasync getAllLinkedAccounts(@User() user: UserAccount) {\n  // Get all external identities for this user\n  const externalIdentities = await this.externalIdentitiesService.findByUserAccount(user.id);\n  \n  // Get linked accounts (if user has merged accounts)\n  const linkedAccounts = await this.accountLinksService.findLinkedAccounts(user.id);\n  \n  return {\n    primaryAccount: {\n      id: user.id,\n      email: user.email,\n      displayName: user.displayName,\n      avatarUrl: user.avatarUrl,\n    },\n    externalIdentities: externalIdentities.map(identity => ({\n      provider: identity.provider,\n      externalId: identity.externalId,\n      email: identity.email,\n      displayName: identity.displayName,\n      linkedAt: identity.createdAt,\n    })),\n    linkedAccounts: linkedAccounts.map(account => ({\n      id: account.id,\n      email: account.email,\n      displayName: account.displayName,\n      linkedAt: account.linkedAt,\n    })),\n  };\n}\n```\n\n#### Find User by Any Identity\n\n```typescript\n@Injectable()\nexport class UserLookupService {\n  constructor(\n    private userAccountsService: UserAccountsService,\n    private externalIdentitiesService: ExternalIdentitiesService,\n  ) {}\n\n  async findUserByAnyIdentity(\n    provider: string,\n    externalId: string,\n  ): Promise<UserAccount | null> {\n    // First, look for direct external identity\n    const externalIdentity = await this.externalIdentitiesService.findByProviderAndExternalId(\n      provider,\n      externalId,\n    );\n\n    if (externalIdentity) {\n      return externalIdentity.userAccount;\n    }\n\n    return null;\n  }\n\n  async findUserByEmail(email: string): Promise<UserAccount[]> {\n    // Find by primary email\n    const primaryUsers = await this.userAccountsService.findByEmail(email);\n    \n    // Find by external identity email\n    const externalIdentities = await this.externalIdentitiesService.findByEmail(email);\n    const externalUsers = externalIdentities.map(identity => identity.userAccount);\n    \n    // Combine and deduplicate\n    const allUsers = [...primaryUsers, ...externalUsers];\n    const uniqueUsers = allUsers.filter((user, index, self) => \n      index === self.findIndex(u => u.id === user.id)\n    );\n    \n    return uniqueUsers;\n  }\n}\n```\n\n### Authentication Flow Examples\n\n#### Multi-Provider Login\n\n```typescript\n@Post('login')\nasync login(@Body() loginDto: { provider?: string, email?: string, password?: string, code?: string }) {\n  if (loginDto.provider && loginDto.code) {\n    // OAuth flow\n    return this.handleOAuthLogin(loginDto.provider, loginDto.code);\n  } else if (loginDto.email && loginDto.password) {\n    // Traditional email/password\n    return this.handleEmailLogin(loginDto.email, loginDto.password);\n  }\n  \n  throw new BadRequestException('Invalid login method');\n}\n\nprivate async handleOAuthLogin(provider: string, code: string) {\n  const userInfo = await this.exchangeCodeForUserInfo(provider, code);\n  const user = await this.userLookupService.findUserByAnyIdentity(provider, userInfo.id);\n  \n  if (!user) {\n    throw new UnauthorizedException('User not found');\n  }\n  \n  return this.generateTokens(user);\n}\n```\n\n#### Account Switching\n\n```typescript\n@Post('switch-account/:accountId')\n@UseGuards(AuthGuard)\nasync switchAccount(\n  @Param('accountId') targetAccountId: string,\n  @User() currentUser: UserAccount,\n) {\n  // Verify the user has access to switch to this account\n  const hasAccess = await this.accountLinksService.canUserAccessAccount(\n    currentUser.id,\n    targetAccountId,\n  );\n  \n  if (!hasAccess) {\n    throw new ForbiddenException('Cannot switch to this account');\n  }\n  \n  const targetUser = await this.userAccountsService.findById(targetAccountId);\n  return this.generateTokens(targetUser);\n}\n```\n\n### Best Practices\n\n1. **Always validate external identities** before linking accounts\n2. **Implement proper consent flows** for account merging\n3. **Store provider-specific data** in the `profileData` field\n4. **Handle email conflicts** gracefully when multiple providers use the same email\n5. **Implement audit logging** for account linking and switching activities\n6. **Use secure tokens** for merge proposals and account operations\n7. **Provide clear UI** for users to manage their linked accounts\n\n## Migration Guide\n\n### From v1.0.0 to v1.1.0\n\n1. **Install the new PostgreSQL dependency**:\n   ```bash\n   npm install pg @types/pg\n   ```\n\n2. **Set up the entity access control schema**:\n   ```bash\n   npx nestjs-iam-cli create --database yourdb --username user --password pass\n   ```\n\n3. **Update your guards** to use the new EntityAccessGuard:\n   ```typescript\n   // Before\n   @UseGuards(AuthGuard, RoleGuard)\n   \n   // After  \n   @UseGuards(AuthGuard, EntityAccessGuard)\n   @EntityAccess({ entityTable: 'companies', requiredRole: 'viewer' })\n   ```\n\n4. **Populate the accounts table** with your existing users:\n   ```typescript\n   // Migration script example\n   async function migrateExistingUsers() {\n     const users = await this.userAccountsService.findAll();\n     \n     for (const user of users) {\n       await this.accountLinksService.createAccount({\n         id: user.id,\n         name: user.displayName,\n         email: user.email,\n       });\n     }\n   }\n   ```\n\n## Contributing\n\nContributions are welcome! Please read our contributing guidelines and submit pull requests to our repository.\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Support\n\nFor support, please open an issue on our GitHub repository or contact the maintainer.\n\n## Changelog\n\n### 1.1.0\n\n- ✨ Added PostgreSQL schema for entity access control\n- 🛠️ Added CLI tool for database schema management\n- 🔒 Added EntityAccessGuard for fine-grained access control\n- 📚 Enhanced documentation with CLI usage examples\n\n### 1.0.0\n\n- Initial release\n- Core IAM functionality\n- TypeORM integration\n- Authentication and authorization features","readmeFilename":"README.md"}