@ciscode/authentication-kit 1.1.6 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +465 -120
  2. package/dist/auth-kit.module.d.ts +6 -4
  3. package/dist/auth-kit.module.js +64 -13
  4. package/dist/config/passport.config.d.ts +2 -1
  5. package/dist/config/passport.config.js +64 -241
  6. package/dist/controllers/auth.controller.d.ts +35 -19
  7. package/dist/controllers/auth.controller.js +155 -488
  8. package/dist/controllers/permissions.controller.d.ts +10 -5
  9. package/dist/controllers/permissions.controller.js +40 -76
  10. package/dist/controllers/roles.controller.d.ts +11 -5
  11. package/dist/controllers/roles.controller.js +49 -66
  12. package/dist/controllers/users.controller.d.ts +15 -7
  13. package/dist/controllers/users.controller.js +52 -227
  14. package/dist/dtos/auth/forgot-password.dto.d.ts +3 -0
  15. package/dist/dtos/auth/forgot-password.dto.js +20 -0
  16. package/dist/dtos/auth/login.dto.d.ts +4 -0
  17. package/dist/dtos/auth/login.dto.js +24 -0
  18. package/dist/dtos/auth/refresh-token.dto.d.ts +3 -0
  19. package/dist/dtos/auth/refresh-token.dto.js +21 -0
  20. package/dist/dtos/auth/register.dto.d.ts +15 -0
  21. package/dist/dtos/auth/register.dto.js +67 -0
  22. package/dist/dtos/auth/resend-verification.dto.d.ts +3 -0
  23. package/dist/dtos/auth/resend-verification.dto.js +20 -0
  24. package/dist/dtos/auth/reset-password.dto.d.ts +4 -0
  25. package/dist/dtos/auth/reset-password.dto.js +25 -0
  26. package/dist/dtos/auth/update-user-role.dto.d.ts +3 -0
  27. package/dist/dtos/auth/update-user-role.dto.js +21 -0
  28. package/dist/dtos/auth/verify-email.dto.d.ts +3 -0
  29. package/dist/dtos/auth/verify-email.dto.js +20 -0
  30. package/dist/dtos/permission/create-permission.dto.d.ts +4 -0
  31. package/dist/dtos/permission/create-permission.dto.js +25 -0
  32. package/dist/dtos/permission/update-permission.dto.d.ts +4 -0
  33. package/dist/dtos/permission/update-permission.dto.js +26 -0
  34. package/dist/dtos/role/create-role.dto.d.ts +4 -0
  35. package/dist/dtos/role/create-role.dto.js +26 -0
  36. package/dist/dtos/role/update-role.dto.d.ts +7 -0
  37. package/dist/dtos/role/update-role.dto.js +35 -0
  38. package/dist/index.d.ts +5 -2
  39. package/dist/index.js +11 -5
  40. package/dist/middleware/admin.decorator.d.ts +1 -0
  41. package/dist/middleware/admin.decorator.js +8 -0
  42. package/dist/middleware/admin.guard.d.ts +7 -0
  43. package/dist/middleware/admin.guard.js +35 -0
  44. package/dist/middleware/authenticate.guard.d.ts +5 -1
  45. package/dist/middleware/authenticate.guard.js +35 -8
  46. package/dist/middleware/role.guard.d.ts +4 -0
  47. package/dist/middleware/role.guard.js +29 -0
  48. package/dist/models/permission.model.d.ts +8 -16
  49. package/dist/models/permission.model.js +25 -14
  50. package/dist/models/role.model.d.ts +9 -28
  51. package/dist/models/role.model.js +26 -14
  52. package/dist/models/user.model.d.ts +22 -62
  53. package/dist/models/user.model.js +90 -41
  54. package/dist/repositories/permission.repository.d.ts +34 -0
  55. package/dist/repositories/permission.repository.js +47 -0
  56. package/dist/repositories/role.repository.d.ts +39 -0
  57. package/dist/repositories/role.repository.js +50 -0
  58. package/dist/repositories/user.repository.d.ts +57 -0
  59. package/dist/repositories/user.repository.js +71 -0
  60. package/dist/services/admin-role.service.d.ts +7 -0
  61. package/dist/services/admin-role.service.js +33 -0
  62. package/dist/services/auth.service.d.ts +49 -0
  63. package/dist/services/auth.service.js +226 -0
  64. package/dist/services/mail.service.d.ts +5 -0
  65. package/dist/services/mail.service.js +39 -0
  66. package/dist/services/oauth.service.d.ts +32 -0
  67. package/dist/services/oauth.service.js +138 -0
  68. package/dist/services/permissions.service.d.ts +19 -0
  69. package/dist/services/permissions.service.js +44 -0
  70. package/dist/services/roles.service.d.ts +23 -0
  71. package/dist/services/roles.service.js +57 -0
  72. package/dist/services/seed.service.d.ts +11 -0
  73. package/dist/services/seed.service.js +50 -0
  74. package/dist/services/users.service.d.ts +30 -0
  75. package/dist/services/users.service.js +88 -0
  76. package/dist/utils/helper.d.ts +1 -0
  77. package/dist/utils/helper.js +4 -0
  78. package/package.json +31 -21
  79. package/dist/config/db.config.d.ts +0 -1
  80. package/dist/config/db.config.js +0 -22
  81. package/dist/controllers/admin.controller.d.ts +0 -4
  82. package/dist/controllers/admin.controller.js +0 -59
  83. package/dist/controllers/password-reset.controller.d.ts +0 -8
  84. package/dist/controllers/password-reset.controller.js +0 -146
  85. package/dist/middleware/auth.guard.d.ts +0 -4
  86. package/dist/middleware/auth.guard.js +0 -39
  87. package/dist/middleware/permission.guard.d.ts +0 -4
  88. package/dist/middleware/permission.guard.js +0 -52
  89. package/dist/models/client.model.d.ts +0 -54
  90. package/dist/models/client.model.js +0 -37
  91. package/dist/models/tenant.model.d.ts +0 -19
  92. package/dist/models/tenant.model.js +0 -15
package/README.md CHANGED
@@ -1,139 +1,484 @@
1
- Auth Service (NestJS, JWT, RBAC)
2
- Internal package - private to the company.
3
- This package is not published on npmjs. Install it only from the company Azure Artifacts feed using a project or user-level .npmrc.
1
+ # AuthKit (NestJS Auth Package)
4
2
 
5
- Authentication and authorization module for NestJS apps.
6
- Provides local email/password auth with lockout, JWT access tokens and refresh, RBAC, and optional OAuth (Microsoft Entra, Google, Facebook).
3
+ A production-ready, comprehensive authentication/authorization kit for NestJS with local auth, OAuth (Google/Microsoft/Facebook), JWT tokens, RBAC, admin user management, email verification, and password reset.
7
4
 
8
- Features
9
- Local auth (email/password) with account lockout policy.
10
- JWT access tokens (Bearer) and refresh endpoint (cookie or body).
11
- RBAC (roles -> permission strings).
12
- Microsoft Entra (Azure AD), Google, Facebook OAuth (optional).
13
- MongoDB/Mongoose models.
5
+ ## Features
14
6
 
15
- Routes are mounted under:
7
+ - **Local Authentication:** Email + password registration & login
8
+ - **OAuth Providers:**
9
+ - Google (ID Token validation + Authorization Code exchange)
10
+ - Microsoft (Entra ID with JWKS verification)
11
+ - Facebook (App token validation)
12
+ - Web redirect flow (Passport)
13
+ - Mobile token/code exchange
14
+ - **JWT Management:**
15
+ - Access tokens (stateless, short-lived)
16
+ - Refresh tokens (long-lived JWTs with automatic invalidation on password change)
17
+ - Email verification tokens (JWT-based links)
18
+ - Password reset tokens (JWT-based links)
19
+ - **Email Verification:** Required before login
20
+ - **Password Reset:** JWT-secured reset link
21
+ - **Admin User Management:** Create, list, ban/unban, delete, assign roles
22
+ - **RBAC (Role-Based Access Control):**
23
+ - Roles linked to users
24
+ - Permissions linked to roles
25
+ - Roles automatically included in JWT payload (Ids)
26
+ - Fine-grained access control
27
+ - **Host App Control:** Package uses host app's Mongoose connection (no DB lock-in)
16
28
 
17
- /api/auth (auth, password reset)
18
- /api/users (user admin)
19
- /api/auth/roles and /api/auth/permissions (RBAC)
20
- /api/admin (admin actions)
29
+ ## Install
21
30
 
22
- Installation
23
-
24
- 1) Install the package
31
+ ```bash
25
32
  npm i @ciscode/authentication-kit
33
+ ```
26
34
 
27
- 2) Required environment variables (host app)
28
- Create a .env in the host project:
35
+ ## Host App Setup
29
36
 
30
- # Server
31
- PORT=3000
32
- NODE_ENV=development
33
- BASE_URL=http://localhost:3000
37
+ ### 1. Environment Variables
34
38
 
35
- # Database (the service connects to this on startup)
36
- MONGO_URI_T=mongodb://127.0.0.1:27017/auth_service
39
+ ```env
40
+ # Database
41
+ MONGO_URI=mongodb://127.0.0.1:27017/app_db
37
42
 
38
- # JWT
39
- JWT_SECRET=change_me
43
+ # JWT Configuration
44
+ JWT_SECRET=your_super_secret_key_change_this
40
45
  JWT_ACCESS_TOKEN_EXPIRES_IN=15m
41
- JWT_REFRESH_SECRET=change_me_too
46
+ JWT_REFRESH_SECRET=your_refresh_secret_change_this
42
47
  JWT_REFRESH_TOKEN_EXPIRES_IN=7d
48
+ JWT_EMAIL_SECRET=your_email_secret_change_this
49
+ JWT_EMAIL_TOKEN_EXPIRES_IN=1d
50
+ JWT_RESET_SECRET=your_reset_secret_change_this
51
+ JWT_RESET_TOKEN_EXPIRES_IN=1h
52
+
53
+ # Email (SMTP)
54
+ SMTP_HOST=smtp.gmail.com
55
+ SMTP_PORT=587
56
+ SMTP_USER=your-email@gmail.com
57
+ SMTP_PASS=your-app-password
58
+ SMTP_SECURE=false
59
+ FROM_EMAIL=noreply@yourapp.com
60
+
61
+ # Frontend URL (for email links)
62
+ FRONTEND_URL=http://localhost:3000
43
63
 
44
- # Lockout policy
45
- MAX_FAILED_LOGIN_ATTEMPTS=5
46
- ACCOUNT_LOCK_TIME_MINUTES=15
64
+ # Google OAuth
65
+ GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
66
+ GOOGLE_CLIENT_SECRET=your-google-client-secret
67
+ GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/google/callback
47
68
 
48
- # (Optional) Microsoft Entra ID (Azure AD)
49
- MICROSOFT_CLIENT_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
50
- MICROSOFT_CLIENT_SECRET=your-secret
51
- MICROSOFT_CALLBACK_URL=${BASE_URL}/api/auth/microsoft/callback
69
+ # Microsoft/Entra ID OAuth
70
+ MICROSOFT_CLIENT_ID=your-microsoft-client-id
71
+ MICROSOFT_CLIENT_SECRET=your-microsoft-client-secret
72
+ MICROSOFT_CALLBACK_URL=http://localhost:3000/api/auth/microsoft/callback
73
+ MICROSOFT_TENANT_ID=common # Optional, defaults to 'common'
52
74
 
53
- Use inside an existing Nest app
54
- The module connects to Mongo on init and mounts its controllers.
75
+ # Facebook OAuth
76
+ FB_CLIENT_ID=your-facebook-app-id
77
+ FB_CLIENT_SECRET=your-facebook-app-secret
78
+ FB_CALLBACK_URL=http://localhost:3000/api/auth/facebook/callback
55
79
 
56
- // app.module.ts (host app)
57
- import { Module } from '@nestjs/common';
58
- import { AuthKitModule } from '@ciscode/authentication-kit';
80
+ # Environment
81
+ NODE_ENV=development
82
+ ```
83
+
84
+ ### 2. Host app example
85
+
86
+ ```typescript
87
+ import { Module, OnModuleInit } from '@nestjs/common';
88
+ import { MongooseModule } from '@nestjs/mongoose';
89
+ import { AuthKitModule, SeedService } from '@ciscode/authentication-kit';
59
90
 
60
91
  @Module({
61
- imports: [AuthKitModule]
92
+ imports: [MongooseModule.forRoot(process.env.MONGO_URI), AuthKitModule],
62
93
  })
63
- export class AppModule {}
64
-
65
- If you need to run it standalone, build and start the package:
66
-
67
- npm run build
68
- npm start
69
-
70
- What is included (routes and behavior)
71
- Auth
72
- POST /api/auth/login - Local login. On success, returns accessToken and may set a refreshToken httpOnly cookie.
73
- POST /api/auth/refresh-token - New access token from a valid refresh token (cookie or body).
74
- POST /api/auth/request-password-reset - Sends a reset token (e.g., by email).
75
- POST /api/auth/reset-password - Consumes the reset token and sets a new password.
76
- GET /api/auth/microsoft - GET /api/auth/microsoft/callback - Optional Microsoft Entra OAuth; issues first-party tokens.
77
- Note: If the Microsoft ID token does not include an email, the response includes `profileIncomplete: true`.
78
- Users
79
- GET /api/users - List users (paginated).
80
- POST /api/users - Create a user.
81
- Additional CRUD endpoints as exposed by controllers.
82
- If `profileIncomplete: true`, update the user profile (e.g., set `email`) via `PUT /api/users/:id`.
83
- Roles and Permissions
84
- GET/POST /api/auth/roles - Manage roles (name, permissions: string[]).
85
- GET /api/auth/permissions - List permission strings and metadata.
86
-
87
- Protecting your own routes (host app)
88
- import { UseGuards } from '@nestjs/common';
89
- import { AuthenticateGuard, hasPermission } from '@ciscode/authentication-kit';
90
-
91
- @UseGuards(AuthenticateGuard, hasPermission('reports:read'))
92
- @Get('reports')
93
- getReports() {
94
- return { ok: true };
95
- }
96
-
97
- Quick start (smoke tests)
98
- Start your host app, then create a user and log in:
99
-
100
- curl -X POST http://localhost:3000/api/users \
101
- -H 'Content-Type: application/json' \
102
- -d '{"email":"a@b.com","password":"Secret123!","name":"Alice"}'
103
-
104
- curl -X POST http://localhost:3000/api/auth/login \
105
- -H 'Content-Type: application/json' \
106
- -d '{"email":"a@b.com","password":"Secret123!"}'
107
- # => { "accessToken": "...", "refreshToken": "..." }
108
-
109
- Call a protected route
110
-
111
- ACCESS=<paste_access_token_here>
112
- curl http://localhost:3000/api/users -H "Authorization: Bearer $ACCESS"
113
-
114
- Refresh token
115
-
116
- curl -X POST http://localhost:3000/api/auth/refresh-token \
117
- -H 'Content-Type: application/json' \
118
- -d '{"refreshToken":"<paste_refresh_token_here>"}'
119
- # => { "accessToken": "..." }
120
-
121
- Microsoft OAuth (optional) - Visit: http://localhost:3000/api/auth/microsoft to complete sign-in.
122
- - Callback: ${BASE_URL}/api/auth/microsoft/callback returns tokens (and may set the refresh cookie).
123
-
124
- CI/CD (Azure Pipelines)
125
- # azure-pipelines.yml (snippet)
126
- - task: npmAuthenticate@0
127
- inputs:
128
- workingFile: .npmrc # optional; the task wires npm auth for subsequent steps
129
-
130
- - script: npm ci
131
- displayName: Install deps
132
- (For GitHub Actions, write a ~/.npmrc with the token from secrets.AZURE_ARTIFACTS_PAT before npm ci.)
133
-
134
- Security notes
135
- Never commit real PATs. Use env vars or CI secrets.
136
- Run behind HTTPS. Rotate JWT and refresh secrets periodically.
137
- Limit login attempts; log auth events for auditing.
138
- License
139
- Internal - Company proprietary.
94
+ export class AppModule implements OnModuleInit {
95
+ constructor(private readonly seed: SeedService) {}
96
+
97
+ async onModuleInit() {
98
+ await this.seed.seedDefaults();
99
+ }
100
+ }
101
+ ```
102
+
103
+ > NOTES:
104
+ >
105
+ > The AuthKit, by default seeds database with default roles and permissions once the host app is bootstraped (logs are generated for info)
106
+ > Default user role, on first register, is 'user' ... Mongoose needs Id to do this relation (the app MUST seed db from the package before anything)
107
+
108
+ ## API Routes
109
+
110
+ ### Local Auth Routes (Public)
111
+
112
+ ```
113
+ POST /api/auth/register
114
+ POST /api/auth/verify-email
115
+ POST /api/auth/resend-verification
116
+ POST /api/auth/login
117
+ POST /api/auth/refresh-token
118
+ POST /api/auth/forgot-password
119
+ POST /api/auth/reset-password
120
+ DELETE /api/auth/account (protected)
121
+ ```
122
+
123
+ ### OAuth Routes - Mobile Exchange (Public)
124
+
125
+ Exchange OAuth provider tokens for app tokens:
126
+
127
+ ```txt
128
+ POST /api/auth/oauth/google { idToken?: string, code?: string }
129
+ POST /api/auth/oauth/microsoft { idToken: string }
130
+ POST /api/auth/oauth/facebook { accessToken: string }
131
+ ```
132
+
133
+ ### OAuth Routes - Web Redirect (Public)
134
+
135
+ Passport-based OAuth flow for web browsers:
136
+
137
+ ```txt
138
+ GET /api/auth/google | Google OAuth
139
+ GET /api/auth/google/callback | Google Redirect (After login)
140
+ GET /api/auth/microsoft | Microsoft OAuth
141
+ GET /api/auth/microsoft/callback | Microsoft Redirect (After login)
142
+ GET /api/auth/facebook | Facebook OAuth
143
+ GET /api/auth/facebook/callback | Facebook Redirect (After login)
144
+ ```
145
+
146
+ ### Admin Routes - Users (Protected with @Admin())
147
+
148
+ ```txt
149
+ POST /api/admin/users |Create user
150
+ GET /api/admin/users?email=...&username=... |List users (with filters)
151
+ PATCH /api/admin/users/:id/ban |Ban user
152
+ PATCH /api/admin/users/:id/unban |Unban user
153
+ PATCH /api/admin/users/:id/roles |Update user roles
154
+ DELETE /api/admin/users/:id |Delete user
155
+ ```
156
+
157
+ ### Admin Routes - Roles (Protected with @Admin())
158
+
159
+ ```txt
160
+ POST /api/admin/roles Create role
161
+ GET /api/admin/roles List all roles
162
+ PUT /api/admin/roles/:id Update role name
163
+ PUT /api/admin/roles/:id/permissions Set role permissions
164
+ DELETE /api/admin/roles/:id Delete role
165
+ ```
166
+
167
+ ### Admin Routes - Permissions (Protected with @Admin())
168
+
169
+ ```txt
170
+ POST /api/admin/permissions Create permission
171
+ GET /api/admin/permissions List all permissions
172
+ PUT /api/admin/permissions/:id Update permission
173
+ DELETE /api/admin/permissions/:id Delete permission
174
+ ```
175
+
176
+ ## Usage Examples
177
+
178
+ ### Register
179
+
180
+ **Request:**
181
+
182
+ ```json
183
+ POST /api/auth/register
184
+ Content-Type: application/json
185
+
186
+ {
187
+ "fullname": {
188
+ "fname": "Test",
189
+ "lname": "User"
190
+ },
191
+ "username": "custom-username",
192
+ "email": "user@example.com",
193
+ "password": "Pa$$word!",
194
+ "phoneNumber": "+1234567890",
195
+ "avatar": "https://example.com/avatar.jpg",
196
+ "jobTitle": "Software Engineer",
197
+ "company": "Ciscode"
198
+ }
199
+ ```
200
+
201
+ **Notes:**
202
+
203
+ - `username` is now **optional**. If not provided, it will be auto-generated as `fname-lname` (e.g., `test-user`)
204
+ - `jobTitle` and `company` are **optional** profile fields
205
+ - All other fields work as before
206
+
207
+ **Response:**
208
+
209
+ ```json
210
+ {
211
+ "id": "507f1f77bcf86cd799439011",
212
+ "email": "user@example.com"
213
+ }
214
+ ```
215
+
216
+ ### Login
217
+
218
+ **Request:**
219
+
220
+ ```json
221
+ POST /api/auth/login
222
+ Content-Type: application/json
223
+
224
+ {
225
+ "email": "user@example.com",
226
+ "password": "Pa$$word!"
227
+ }
228
+ ```
229
+
230
+ **Response:**
231
+
232
+ ```json
233
+ {
234
+ "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
235
+ "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
236
+ }
237
+ ```
238
+
239
+ _Note: `refreshToken` is also set in httpOnly cookie_
240
+
241
+ ### Verify Email
242
+
243
+ **Request:**
244
+
245
+ ```json
246
+ POST /api/auth/verify-email
247
+ Content-Type: application/json
248
+
249
+ {
250
+ "token": "email-verification-token-from-email"
251
+ }
252
+ ```
253
+
254
+ **Response:**
255
+
256
+ ```json
257
+ {
258
+ "ok": true
259
+ }
260
+ ```
261
+
262
+ ### Refresh Token
263
+
264
+ **Request (from body):**
265
+
266
+ ```json
267
+ POST /api/auth/refresh-token
268
+ Content-Type: application/json
269
+
270
+ {
271
+ "refreshToken": "refresh-token-value"
272
+ }
273
+ ```
274
+
275
+ **OR (from cookie - automatic):**
276
+
277
+ ```json
278
+ POST /api/auth/refresh-token
279
+ Cookie: refreshToken=refresh-token-value
280
+ ```
281
+
282
+ **Response:**
283
+
284
+ ```json
285
+ {
286
+ "accessToken": "new-access-token",
287
+ "refreshToken": "new-refresh-token"
288
+ }
289
+ ```
290
+
291
+ ### OAuth Google (Mobile Exchange)
292
+
293
+ **Request (with ID Token):**
294
+
295
+ ```json
296
+ POST /api/auth/oauth/google
297
+ Content-Type: application/json
298
+
299
+ {
300
+ "idToken": "google-id-token-from-client"
301
+ }
302
+ ```
303
+
304
+ **OR (with Authorization Code):**
305
+
306
+ ```json
307
+ POST /api/auth/oauth/google
308
+ Content-Type: application/json
309
+
310
+ {
311
+ "code": "authorization-code-from-google"
312
+ }
313
+ ```
314
+
315
+ **Response:**
316
+
317
+ ```json
318
+ {
319
+ "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
320
+ "refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
321
+ }
322
+ ```
323
+
324
+ ### Delete Account
325
+
326
+ **Request:**
327
+
328
+ ```json
329
+ DELETE /api/auth/account
330
+ Authorization: Bearer access-token
331
+ ```
332
+
333
+ **Response:**
334
+
335
+ ```json
336
+ {
337
+ "ok": true
338
+ }
339
+ ```
340
+
341
+ ## Guards & Decorators
342
+
343
+ **AuthenticateGuard:** Protects routes that require authentication. (No Access if not authenticated)
344
+ **Admin Decorator:** Restricts routes to admin users only. (No Access if not an admin)
345
+
346
+ ## JWT Token Structure
347
+
348
+ ### Access Token Payload
349
+
350
+ ```json
351
+ {
352
+ "sub": "user-id",
353
+ "roles": ["ids"],
354
+ "iat": 1672531200,
355
+ "exp": 1672531900
356
+ }
357
+ ```
358
+
359
+ ### Refresh Token Payload
360
+
361
+ ```json
362
+ {
363
+ "sub": "user-id",
364
+ "purpose": "refresh",
365
+ "iat": 1672531200,
366
+ "exp": 1672617600
367
+ }
368
+ ```
369
+
370
+ **Security Note:** Refresh tokens are automatically invalidated if user changes password. The `passwordChangedAt` timestamp is checked during token refresh.
371
+
372
+ ## Seeding
373
+
374
+ On app startup via `onModuleInit()`, the following are created:
375
+
376
+ **Roles:**
377
+
378
+ - `admin` - Full permissions
379
+ - `user` - No default permissions
380
+
381
+ **Permissions:**
382
+
383
+ - `users:manage` - Create, list, ban, delete users
384
+ - `roles:manage` - Create, list, update, delete roles
385
+ - `permissions:manage` - Create, list, update, delete permissions
386
+
387
+ All permissions are assigned to the `admin` role.
388
+
389
+ ## User Model
390
+
391
+ ```typescript
392
+ {
393
+ _id: ObjectId,
394
+ fullname: {
395
+ fname: string,
396
+ lname: string
397
+ },
398
+ username: string (unique, 3-30 chars, auto-generated as fname-lname if not provided),
399
+ email: string (unique, validated),
400
+ phoneNumber?: string (unique, 10-14 digits),
401
+ avatar?: string (default: 'default.jpg'),
402
+ jobTitle?: string,
403
+ company?: string,
404
+ password: string (hashed, min 6 chars),
405
+ roles: ObjectId[] (references Role),
406
+ isVerified: boolean (default: false),
407
+ isBanned: boolean (default: false),
408
+ passwordChangedAt: Date,
409
+ createdAt: Date,
410
+ updatedAt: Date
411
+ }
412
+ ```
413
+
414
+ ## Role Model
415
+
416
+ ```typescript
417
+ {
418
+ _id: ObjectId,
419
+ name: string (unique),
420
+ permissions: ObjectId[] (references Permission),
421
+ createdAt: Date,
422
+ updatedAt: Date
423
+ }
424
+ ```
425
+
426
+ ## Permission Model
427
+
428
+ ```typescript
429
+ {
430
+ _id: ObjectId,
431
+ name: string (unique),
432
+ description?: string,
433
+ createdAt: Date,
434
+ updatedAt: Date
435
+ }
436
+ ```
437
+
438
+ ## Important Notes
439
+
440
+ - **Database:** AuthKit does NOT manage MongoDB connection. Your host app must provide the connection via `MongooseModule.forRoot()`.
441
+ - **Stateless:** JWTs are stateless; refresh tokens are signed JWTs (not stored in DB).
442
+ - **Email Verification Required:** Users cannot login until they verify their email.
443
+ - **Password Changes Invalidate Tokens:** All refresh tokens become invalid immediately after password change.
444
+ - **OAuth Auto-Registration:** Users logging in via OAuth are automatically created with verified status.
445
+ - **Cookie + Body Support:** Refresh tokens can be passed via httpOnly cookies OR request body.
446
+ - **Admin Access:** Routes under `/api/admin/*` require the `admin` role (enforced by `@Admin()` decorator).
447
+
448
+ ## Error Handling
449
+
450
+ The package throws errors with descriptive messages. Your host app should catch and format them appropriately:
451
+
452
+ ```typescript
453
+ try {
454
+ await authService.login(dto);
455
+ } catch (error) {
456
+ // Possible errors:
457
+ // "Invalid credentials."
458
+ // "Account banned."
459
+ // "Email not verified."
460
+ // "User not found."
461
+ // "JWT_SECRET is not set"
462
+ // etc.
463
+ }
464
+ ```
465
+
466
+ ## Development
467
+
468
+ ```bash
469
+ npm run build # Compile TypeScript + alias paths
470
+ npm run start # Run standalone (if applicable)
471
+ npm run test # Run tests (currently no tests defined)
472
+ ```
473
+
474
+ ## License
475
+
476
+ MIT
477
+
478
+ ## Author
479
+
480
+ Ciscode
481
+
482
+ ---
483
+
484
+ **Version:** 1.2.0
@@ -1,7 +1,9 @@
1
1
  import 'dotenv/config';
2
- import { MiddlewareConsumer, NestModule, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
3
- export declare class AuthKitModule implements NestModule, OnModuleInit, OnModuleDestroy {
4
- onModuleInit(): Promise<void>;
5
- onModuleDestroy(): Promise<void>;
2
+ import { MiddlewareConsumer, NestModule, OnModuleInit } from '@nestjs/common';
3
+ import { OAuthService } from './services/oauth.service';
4
+ export declare class AuthKitModule implements NestModule, OnModuleInit {
5
+ private readonly oauth;
6
+ constructor(oauth: OAuthService);
7
+ onModuleInit(): void;
6
8
  configure(consumer: MiddlewareConsumer): void;
7
9
  }