mbkauthe 3.0.0 โ 3.2.0
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.
- package/README.md +98 -16
- package/docs/api.md +212 -117
- package/docs/db.md +71 -16
- package/docs/env.md +91 -8
- package/index.d.ts +59 -21
- package/lib/config/index.js +48 -1
- package/lib/main.js +27 -1
- package/lib/middleware/index.js +4 -2
- package/lib/routes/auth.js +25 -3
- package/lib/routes/misc.js +29 -17
- package/lib/routes/oauth.js +379 -264
- package/lib/utils/response.js +2 -2
- package/package.json +30 -10
- package/test.spec.js +196 -0
- package/views/2fa.handlebars +2 -2
- package/views/loginmbkauthe.handlebars +35 -5
- package/views/sharedStyles.handlebars +5 -0
- package/views/showmessage.handlebars +27 -1
- package/.env.example +0 -3
- package/.github/PACKAGE.md +0 -17
- package/.github/workflows/codeql.yml +0 -98
- package/.github/workflows/publish.yml +0 -87
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# MBKAuthe v3.
|
|
1
|
+
# MBKAuthe v3.2 - Authentication System for Node.js
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/mbkauthe)
|
|
4
4
|
[](LICENSE)
|
|
@@ -16,19 +16,20 @@
|
|
|
16
16
|
<img height="48px" src="https://handlebarsjs.com/handlebars-icon.svg" alt="Handlebars" />
|
|
17
17
|
</p>
|
|
18
18
|
|
|
19
|
-
**MBKAuth v3.
|
|
19
|
+
**MBKAuth v3.2** is a production-ready authentication system for Node.js applications. Built with Express and PostgreSQL, it provides secure authentication, 2FA, role-based access, and OAuth integration (GitHub & Google) out of the box.
|
|
20
20
|
|
|
21
21
|
## โจ Key Features
|
|
22
22
|
|
|
23
23
|
- ๐ Secure password authentication with PBKDF2 hashing
|
|
24
24
|
- ๐ PostgreSQL session management with cross-subdomain support
|
|
25
25
|
- ๐ฑ Optional TOTP-based 2FA with trusted device memory
|
|
26
|
-
- ๐ GitHub
|
|
26
|
+
- ๐ OAuth integration (GitHub & Google)
|
|
27
27
|
- ๐ฅ Role-based access control (SuperAdmin, NormalUser, Guest)
|
|
28
28
|
- ๐ฏ Multi-application user management
|
|
29
|
-
- ๐ก๏ธ CSRF protection & rate limiting
|
|
29
|
+
- ๐ก๏ธ CSRF protection & advanced rate limiting
|
|
30
30
|
- ๐ Easy Express.js integration
|
|
31
31
|
- ๐จ Customizable Handlebars templates
|
|
32
|
+
- ๐ Enhanced security with session fixation prevention
|
|
32
33
|
|
|
33
34
|
## ๐ฆ Installation
|
|
34
35
|
|
|
@@ -48,10 +49,18 @@ IS_DEPLOYED=false
|
|
|
48
49
|
DOMAIN=localhost
|
|
49
50
|
LOGIN_DB=postgresql://user:pass@localhost:5432/db
|
|
50
51
|
|
|
51
|
-
# Optional
|
|
52
|
+
# Optional Features
|
|
52
53
|
MBKAUTH_TWO_FA_ENABLE=false
|
|
53
54
|
COOKIE_EXPIRE_TIME=2
|
|
55
|
+
|
|
56
|
+
# OAuth Configuration (Optional)
|
|
54
57
|
GITHUB_LOGIN_ENABLED=false
|
|
58
|
+
GITHUB_CLIENT_ID=
|
|
59
|
+
GITHUB_CLIENT_SECRET=
|
|
60
|
+
|
|
61
|
+
GOOGLE_LOGIN_ENABLED=false
|
|
62
|
+
GOOGLE_CLIENT_ID=
|
|
63
|
+
GOOGLE_CLIENT_SECRET=
|
|
55
64
|
```
|
|
56
65
|
|
|
57
66
|
**2. Set Up Database**
|
|
@@ -110,6 +119,30 @@ app.get('/admin', validateSession, checkRolePermission(['SuperAdmin']), (req, re
|
|
|
110
119
|
app.listen(3000);
|
|
111
120
|
```
|
|
112
121
|
|
|
122
|
+
## ๐งช Testing
|
|
123
|
+
|
|
124
|
+
MBKAuthe includes comprehensive test coverage for all authentication features:
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
# Run all tests
|
|
128
|
+
npm test
|
|
129
|
+
|
|
130
|
+
# Run tests in watch mode (auto-rerun on changes)
|
|
131
|
+
npm run test:watch
|
|
132
|
+
|
|
133
|
+
# Run with development flags
|
|
134
|
+
npm run dev
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
**Test Coverage:**
|
|
138
|
+
- โ
Authentication flows (login, 2FA, logout)
|
|
139
|
+
- โ
OAuth integration (GitHub)
|
|
140
|
+
- โ
Session management and security
|
|
141
|
+
- โ
Role-based access control
|
|
142
|
+
- โ
API endpoints and error handling
|
|
143
|
+
- โ
CSRF protection and rate limiting
|
|
144
|
+
- โ
Static asset serving
|
|
145
|
+
|
|
113
146
|
## ๐ Architecture (v3.0)
|
|
114
147
|
|
|
115
148
|
```
|
|
@@ -148,22 +181,42 @@ app.post('/api/data', authenticate(process.env.API_TOKEN), handler);
|
|
|
148
181
|
|
|
149
182
|
### Built-in Routes
|
|
150
183
|
|
|
151
|
-
|
|
184
|
+
**Authentication Routes:**
|
|
185
|
+
- `GET /login`, `/signin` - Redirect to main login page
|
|
186
|
+
- `GET /mbkauthe/login` - Login page (8/min rate limit)
|
|
152
187
|
- `POST /mbkauthe/api/login` - Login endpoint (8/min rate limit)
|
|
153
188
|
- `POST /mbkauthe/api/logout` - Logout endpoint (10/min rate limit)
|
|
154
|
-
- `GET /mbkauthe/2fa` - 2FA page (if enabled)
|
|
155
|
-
- `POST /mbkauthe/api/verify-2fa` - 2FA verification (5/min rate limit)
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
- `GET /mbkauthe/
|
|
189
|
+
- `GET /mbkauthe/2fa` - 2FA verification page (if enabled)
|
|
190
|
+
- `POST /mbkauthe/api/verify-2fa` - 2FA verification API (5/min rate limit)
|
|
191
|
+
|
|
192
|
+
**OAuth Routes:**
|
|
193
|
+
- `GET /mbkauthe/api/github/login` - GitHub OAuth initiation (10/5min rate limit)
|
|
194
|
+
- `GET /mbkauthe/api/github/login/callback` - GitHub OAuth callback
|
|
195
|
+
- `GET /mbkauthe/api/google/login` - Google OAuth initiation (10/5min rate limit)
|
|
196
|
+
- `GET /mbkauthe/api/google/login/callback` - Google OAuth callback
|
|
197
|
+
|
|
198
|
+
**Information & Utility Routes:**
|
|
199
|
+
- `GET /mbkauthe/info`, `/mbkauthe/i` - Version & config info (8/min rate limit)
|
|
200
|
+
- `GET /mbkauthe/ErrorCode` - Error code documentation
|
|
201
|
+
- `GET /mbkauthe/test` - Test authentication status (8/min rate limit)
|
|
202
|
+
|
|
203
|
+
**Static Asset Routes:**
|
|
204
|
+
- `GET /mbkauthe/main.js` - Client-side JavaScript utilities
|
|
205
|
+
- `GET /mbkauthe/bg.webp` - Background image for auth pages
|
|
206
|
+
- `GET /icon.svg` - Application SVG icon (root level)
|
|
207
|
+
- `GET /favicon.ico`, `/icon.ico` - Application favicon
|
|
208
|
+
|
|
209
|
+
**Admin API Routes:**
|
|
210
|
+
- `POST /mbkauthe/api/terminateAllSessions` - Terminate all sessions (admin only)
|
|
159
211
|
|
|
160
212
|
## ๐ Security Features
|
|
161
213
|
|
|
162
|
-
- **Rate Limiting**: Login (8/min), Logout (10/min), 2FA (5/min), OAuth (10/5min)
|
|
163
|
-
- **CSRF Protection**: All
|
|
214
|
+
- **Rate Limiting**: Login (8/min), Logout (10/min), 2FA (5/min), OAuth (10/5min), Admin (3/5min)
|
|
215
|
+
- **CSRF Protection**: All state-changing routes protected with token validation
|
|
164
216
|
- **Secure Cookies**: httpOnly, sameSite, secure in production
|
|
165
217
|
- **Password Hashing**: PBKDF2 with 100k iterations
|
|
166
|
-
- **Session Security**: PostgreSQL-backed, automatic cleanup
|
|
218
|
+
- **Session Security**: PostgreSQL-backed, automatic cleanup, session fixation prevention
|
|
219
|
+
- **OAuth Security**: State validation, token expiry handling, secure callback validation
|
|
167
220
|
|
|
168
221
|
## ๐ฑ Two-Factor Authentication
|
|
169
222
|
|
|
@@ -179,7 +232,9 @@ CREATE TABLE "TwoFA" (
|
|
|
179
232
|
|
|
180
233
|
Users can mark devices as trusted to skip 2FA for configurable duration.
|
|
181
234
|
|
|
182
|
-
## ๐
|
|
235
|
+
## ๐ OAuth Integration
|
|
236
|
+
|
|
237
|
+
### GitHub OAuth
|
|
183
238
|
|
|
184
239
|
**Setup:**
|
|
185
240
|
|
|
@@ -202,6 +257,32 @@ CREATE TABLE user_github (
|
|
|
202
257
|
);
|
|
203
258
|
```
|
|
204
259
|
|
|
260
|
+
### Google OAuth
|
|
261
|
+
|
|
262
|
+
**Setup:**
|
|
263
|
+
|
|
264
|
+
1. Create Google OAuth 2.0 Client in [Google Cloud Console](https://console.cloud.google.com/)
|
|
265
|
+
2. Add authorized redirect URI: `https://yourdomain.com/mbkauthe/api/google/login/callback`
|
|
266
|
+
3. Configure environment:
|
|
267
|
+
```env
|
|
268
|
+
GOOGLE_LOGIN_ENABLED=true
|
|
269
|
+
GOOGLE_CLIENT_ID=your_client_id
|
|
270
|
+
GOOGLE_CLIENT_SECRET=your_client_secret
|
|
271
|
+
```
|
|
272
|
+
4. Create table:
|
|
273
|
+
```sql
|
|
274
|
+
CREATE TABLE user_google (
|
|
275
|
+
id SERIAL PRIMARY KEY,
|
|
276
|
+
user_name VARCHAR(50) REFERENCES "Users"("UserName"),
|
|
277
|
+
google_id VARCHAR(255) UNIQUE,
|
|
278
|
+
google_email VARCHAR(255),
|
|
279
|
+
access_token VARCHAR(255),
|
|
280
|
+
created_at TIMESTAMP DEFAULT NOW()
|
|
281
|
+
);
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
**Note:** Users must link their OAuth accounts before they can use OAuth login.
|
|
285
|
+
|
|
205
286
|
## ๐จ Customization
|
|
206
287
|
|
|
207
288
|
**Redirect URL:**
|
|
@@ -245,8 +326,9 @@ const result = await dblogin.query('SELECT * FROM "Users"');
|
|
|
245
326
|
## ๐ Documentation
|
|
246
327
|
|
|
247
328
|
- [API Documentation](docs/api.md) - Complete API reference
|
|
248
|
-
- [Database Guide](docs/db.md) - Schema details
|
|
329
|
+
- [Database Guide](docs/db.md) - Schema details
|
|
249
330
|
- [Environment Config](docs/env.md) - Configuration options
|
|
331
|
+
- [Error Messages](docs/error-messages.md) - Error code reference
|
|
250
332
|
|
|
251
333
|
## ๐ License
|
|
252
334
|
|
package/docs/api.md
CHANGED
|
@@ -55,14 +55,66 @@ When a user logs in, MBKAuthe creates a session and sets the following cookies:
|
|
|
55
55
|
|
|
56
56
|
### Public Endpoints
|
|
57
57
|
|
|
58
|
+
#### `GET /login`
|
|
59
|
+
|
|
60
|
+
Redirect route that forwards to the main login page.
|
|
61
|
+
|
|
62
|
+
**Rate Limit:** No rate limiting applied
|
|
63
|
+
|
|
64
|
+
**Query Parameters:**
|
|
65
|
+
- All query parameters are preserved and forwarded
|
|
66
|
+
|
|
67
|
+
**Response:** 302 redirect to `/mbkauthe/login`
|
|
68
|
+
|
|
69
|
+
**Example:**
|
|
70
|
+
```
|
|
71
|
+
GET /login?redirect=/dashboard
|
|
72
|
+
โ Redirects to: /mbkauthe/login?redirect=/dashboard
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
#### `GET /signin`
|
|
78
|
+
|
|
79
|
+
Alias redirect route that forwards to the main login page.
|
|
80
|
+
|
|
81
|
+
**Rate Limit:** No rate limiting applied
|
|
82
|
+
|
|
83
|
+
**Query Parameters:**
|
|
84
|
+
- All query parameters are preserved and forwarded
|
|
85
|
+
|
|
86
|
+
**Response:** 302 redirect to `/mbkauthe/login`
|
|
87
|
+
|
|
88
|
+
**Example:**
|
|
89
|
+
```
|
|
90
|
+
GET /signin
|
|
91
|
+
โ Redirects to: /mbkauthe/login
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
---
|
|
95
|
+
|
|
58
96
|
#### `GET /mbkauthe/login`
|
|
59
97
|
|
|
60
|
-
Renders the login page.
|
|
98
|
+
Renders the main login page.
|
|
99
|
+
|
|
100
|
+
**Rate Limit:** 8 requests per minute (exempt for logged-in users)
|
|
101
|
+
|
|
102
|
+
**CSRF Protection:** Required (token included in form)
|
|
61
103
|
|
|
62
104
|
**Query Parameters:**
|
|
63
105
|
- `redirect` (optional) - URL to redirect after successful login
|
|
64
106
|
|
|
65
|
-
**Response:** HTML page
|
|
107
|
+
**Response:** HTML page with login form
|
|
108
|
+
|
|
109
|
+
**Template Variables:**
|
|
110
|
+
- `githubLoginEnabled` - Whether GitHub OAuth is enabled
|
|
111
|
+
- `googleLoginEnabled` - Whether Google OAuth is enabled
|
|
112
|
+
- `customURL` - Redirect URL after login
|
|
113
|
+
- `userLoggedIn` - Whether user is already authenticated
|
|
114
|
+
- `username` - Current username if logged in
|
|
115
|
+
- `version` - MBKAuthe version
|
|
116
|
+
- `appName` - Application name
|
|
117
|
+
- `csrfToken` - CSRF protection token
|
|
66
118
|
|
|
67
119
|
**Example:**
|
|
68
120
|
```
|
|
@@ -275,13 +327,17 @@ fetch('/mbkauthe/api/logout', {
|
|
|
275
327
|
|
|
276
328
|
Terminates all active sessions across all users (admin only).
|
|
277
329
|
|
|
278
|
-
**Authentication:** API token required
|
|
330
|
+
**Authentication:** API token required (via `authenticate` middleware)
|
|
331
|
+
|
|
332
|
+
**Rate Limit:** 3 requests per 5 minutes
|
|
279
333
|
|
|
280
334
|
**Headers:**
|
|
281
335
|
```
|
|
282
|
-
Authorization: your-
|
|
336
|
+
Authorization: your-main-secret-token
|
|
283
337
|
```
|
|
284
338
|
|
|
339
|
+
**Request Body:** None required
|
|
340
|
+
|
|
285
341
|
**Success Response (200 OK):**
|
|
286
342
|
```json
|
|
287
343
|
{
|
|
@@ -298,16 +354,29 @@ Authorization: your-api-token
|
|
|
298
354
|
| 500 | Failed to terminate sessions |
|
|
299
355
|
| 500 | Internal Server Error |
|
|
300
356
|
|
|
357
|
+
**Implementation Details:**
|
|
358
|
+
- Clears all user session IDs in the database (`Users` table) where sessions exist
|
|
359
|
+
- Deletes all active session records from the `session` table
|
|
360
|
+
- Destroys the current request session
|
|
361
|
+
- Clears session cookies
|
|
362
|
+
- Runs database operations in parallel for better performance
|
|
363
|
+
- Uses optimized queries with WHERE clauses to avoid unnecessary updates
|
|
364
|
+
|
|
301
365
|
**Example Request:**
|
|
302
366
|
```javascript
|
|
303
367
|
fetch('/mbkauthe/api/terminateAllSessions', {
|
|
304
368
|
method: 'POST',
|
|
305
369
|
headers: {
|
|
306
|
-
'Authorization':
|
|
370
|
+
'Authorization': process.env.MAIN_SECRET_TOKEN,
|
|
371
|
+
'Content-Type': 'application/json'
|
|
307
372
|
}
|
|
308
373
|
})
|
|
309
374
|
.then(response => response.json())
|
|
310
|
-
.then(data =>
|
|
375
|
+
.then(data => {
|
|
376
|
+
if (data.success) {
|
|
377
|
+
console.log('All sessions terminated successfully');
|
|
378
|
+
}
|
|
379
|
+
});
|
|
311
380
|
```
|
|
312
381
|
|
|
313
382
|
---
|
|
@@ -363,6 +432,10 @@ GET /mbkauthe/ErrorCode
|
|
|
363
432
|
|
|
364
433
|
Serves the client-side JavaScript file containing helper functions for authentication operations.
|
|
365
434
|
|
|
435
|
+
**Rate Limit:** No rate limiting applied
|
|
436
|
+
|
|
437
|
+
**Cache:** Cached for 1 year (max-age=31536000)
|
|
438
|
+
|
|
366
439
|
**Purpose:** Provides frontend JavaScript utilities including:
|
|
367
440
|
- `logout()` - Logout function with confirmation dialog and cache clearing
|
|
368
441
|
- `logoutuser()` - Alias for logout function
|
|
@@ -396,46 +469,20 @@ Serves the client-side JavaScript file containing helper functions for authentic
|
|
|
396
469
|
- Clears cookies
|
|
397
470
|
- Forces page reload
|
|
398
471
|
|
|
399
|
-
|
|
400
|
-
---
|
|
401
|
-
|
|
402
|
-
#### `GET /mbkauthe/ErrorCode`
|
|
403
|
-
|
|
404
|
-
Displays comprehensive error code documentation with descriptions and user messages.
|
|
405
|
-
|
|
406
|
-
**Response:** HTML page showing:
|
|
407
|
-
- All error codes organized by category
|
|
408
|
-
- Error code ranges (Authentication, 2FA, Session, Authorization, etc.)
|
|
409
|
-
- User-friendly messages and hints for each error
|
|
410
|
-
- Dynamically generated from `lib/utils/errors.js`
|
|
411
|
-
|
|
412
|
-
**Categories:**
|
|
413
|
-
- **600-699**: Authentication Errors
|
|
414
|
-
- **700-799**: Two-Factor Authentication Errors
|
|
415
|
-
- **800-899**: Session Management Errors
|
|
416
|
-
- **900-999**: Authorization Errors
|
|
417
|
-
- **1000-1099**: Input Validation Errors
|
|
418
|
-
- **1100-1199**: Rate Limiting Errors
|
|
419
|
-
- **1200-1299**: Server Errors
|
|
420
|
-
- **1300-1399**: OAuth Errors
|
|
421
|
-
|
|
422
|
-
**Note:** This page is automatically synchronized with the error definitions in the codebase. Adding new errors only requires updating `lib/utils/errors.js` and the category code array.
|
|
423
|
-
|
|
424
|
-
**Usage:**
|
|
425
|
-
```
|
|
426
|
-
GET /mbkauthe/ErrorCode
|
|
427
|
-
```
|
|
428
|
-
|
|
429
472
|
---
|
|
430
473
|
|
|
431
474
|
#### `GET /icon.svg`
|
|
432
475
|
|
|
433
|
-
Serves the application's SVG icon file.
|
|
476
|
+
Serves the application's SVG icon file from the root level.
|
|
477
|
+
|
|
478
|
+
**Rate Limit:** No rate limiting applied
|
|
434
479
|
|
|
435
480
|
**Response:** SVG image file (Content-Type: image/svg+xml)
|
|
436
481
|
|
|
437
482
|
**Cache:** Cached for 1 year (max-age=31536000)
|
|
438
483
|
|
|
484
|
+
**Note:** This route is mounted at the root level (not under `/mbkauthe`)
|
|
485
|
+
|
|
439
486
|
**Usage:**
|
|
440
487
|
```html
|
|
441
488
|
<img src="/icon.svg" alt="App Icon">
|
|
@@ -512,12 +559,16 @@ GET /mbkauthe/test
|
|
|
512
559
|
|
|
513
560
|
### OAuth Endpoints
|
|
514
561
|
|
|
515
|
-
####
|
|
562
|
+
#### GitHub OAuth
|
|
563
|
+
|
|
564
|
+
##### `GET /mbkauthe/api/github/login`
|
|
516
565
|
|
|
517
566
|
Initiates the GitHub OAuth authentication flow.
|
|
518
567
|
|
|
519
568
|
**Rate Limit:** 10 requests per 5 minutes
|
|
520
569
|
|
|
570
|
+
**CSRF Protection:** Required (state parameter used for validation)
|
|
571
|
+
|
|
521
572
|
**Query Parameters:**
|
|
522
573
|
- `redirect` (optional) - Relative URL to redirect after successful authentication (must start with `/` to prevent open redirect attacks)
|
|
523
574
|
|
|
@@ -535,15 +586,16 @@ GET /mbkauthe/api/github/login?redirect=/dashboard
|
|
|
535
586
|
|
|
536
587
|
**Workflow:**
|
|
537
588
|
1. User clicks "Login with GitHub"
|
|
538
|
-
2.
|
|
539
|
-
3.
|
|
540
|
-
4.
|
|
541
|
-
5.
|
|
542
|
-
6.
|
|
589
|
+
2. CSRF token generated and stored in session
|
|
590
|
+
3. Redirects to GitHub for authorization
|
|
591
|
+
4. GitHub redirects back to callback URL
|
|
592
|
+
5. System verifies GitHub account is linked
|
|
593
|
+
6. If 2FA enabled, prompts for 2FA
|
|
594
|
+
7. Creates session and redirects to specified URL
|
|
543
595
|
|
|
544
596
|
---
|
|
545
597
|
|
|
546
|
-
|
|
598
|
+
##### `GET /mbkauthe/api/github/login/callback`
|
|
547
599
|
|
|
548
600
|
Handles the OAuth callback from GitHub after user authorization.
|
|
549
601
|
|
|
@@ -583,6 +635,104 @@ WHERE ug.github_id = $1
|
|
|
583
635
|
|
|
584
636
|
---
|
|
585
637
|
|
|
638
|
+
#### Google OAuth
|
|
639
|
+
|
|
640
|
+
##### `GET /mbkauthe/api/google/login`
|
|
641
|
+
|
|
642
|
+
Initiates the Google OAuth 2.0 authentication flow.
|
|
643
|
+
|
|
644
|
+
**Rate Limit:** 10 requests per 5 minutes
|
|
645
|
+
|
|
646
|
+
**CSRF Protection:** Required (state parameter used for validation)
|
|
647
|
+
|
|
648
|
+
**Query Parameters:**
|
|
649
|
+
- `redirect` (optional) - Relative URL to redirect after successful authentication (must start with `/` to prevent open redirect attacks)
|
|
650
|
+
|
|
651
|
+
**Response:** Redirects to Google OAuth authorization page
|
|
652
|
+
|
|
653
|
+
**Prerequisites:**
|
|
654
|
+
- `GOOGLE_LOGIN_ENABLED=true` in environment
|
|
655
|
+
- Valid `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` configured
|
|
656
|
+
- User's Google account must be linked to an MBKAuth account in `user_google` table
|
|
657
|
+
|
|
658
|
+
**Example:**
|
|
659
|
+
```
|
|
660
|
+
GET /mbkauthe/api/google/login?redirect=/dashboard
|
|
661
|
+
```
|
|
662
|
+
|
|
663
|
+
**Workflow:**
|
|
664
|
+
1. User clicks "Login with Google"
|
|
665
|
+
2. CSRF token generated and stored in session
|
|
666
|
+
3. Redirects to Google for authorization
|
|
667
|
+
4. Google redirects back to callback URL
|
|
668
|
+
5. System verifies Google account is linked
|
|
669
|
+
6. If 2FA enabled, prompts for 2FA
|
|
670
|
+
7. Creates session and redirects to specified URL
|
|
671
|
+
|
|
672
|
+
**Error Responses:**
|
|
673
|
+
- **Configuration Error**: Returns 500 if Google OAuth credentials are not properly configured
|
|
674
|
+
- **Disabled**: Returns 403 if `GOOGLE_LOGIN_ENABLED` is false
|
|
675
|
+
|
|
676
|
+
---
|
|
677
|
+
|
|
678
|
+
##### `GET /mbkauthe/api/google/login/callback`
|
|
679
|
+
|
|
680
|
+
Handles the OAuth callback from Google after user authorization.
|
|
681
|
+
|
|
682
|
+
**Rate Limit:** Inherited from OAuth rate limiter (10 requests per 5 minutes)
|
|
683
|
+
|
|
684
|
+
**Query Parameters:**
|
|
685
|
+
- `code` - Authorization code from Google (automatically provided)
|
|
686
|
+
- `state` - State parameter for CSRF protection (automatically provided)
|
|
687
|
+
|
|
688
|
+
**Response:**
|
|
689
|
+
- Redirects to 2FA page if 2FA is enabled for the user
|
|
690
|
+
- Redirects to `loginRedirectURL` or stored redirect URL if 2FA is not required
|
|
691
|
+
- Renders error page if authentication fails
|
|
692
|
+
|
|
693
|
+
**Error Handling:**
|
|
694
|
+
- **Google Not Linked**: Returns error if Google account is not in `user_google` table
|
|
695
|
+
- **Account Inactive**: Returns error if user account is deactivated
|
|
696
|
+
- **Not Authorized**: Returns error if user is not allowed to access the application
|
|
697
|
+
- **Google Auth Error**: Returns error for any OAuth-related failures
|
|
698
|
+
- **Token Error**: Handles expired or invalid OAuth tokens with user-friendly message
|
|
699
|
+
- **CSRF Validation Failed**: Returns 403 if state parameter doesn't match
|
|
700
|
+
|
|
701
|
+
**Success Flow:**
|
|
702
|
+
```
|
|
703
|
+
Google โ /api/google/login/callback
|
|
704
|
+
โ (CSRF Validation)
|
|
705
|
+
โ (If 2FA enabled) โ /mbkauthe/2fa
|
|
706
|
+
โ (If no 2FA) โ loginRedirectURL or stored redirect
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
**Database Query:**
|
|
710
|
+
```sql
|
|
711
|
+
SELECT ug.*, u."UserName", u."Role", u."Active", u."AllowedApps", u."id"
|
|
712
|
+
FROM user_google ug
|
|
713
|
+
JOIN "Users" u ON ug.user_name = u."UserName"
|
|
714
|
+
WHERE ug.google_id = $1
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
**Note:** This endpoint is automatically called by Google and should not be accessed directly by users.
|
|
718
|
+
|
|
719
|
+
---
|
|
720
|
+
|
|
721
|
+
#### OAuth Security Features
|
|
722
|
+
|
|
723
|
+
Both GitHub and Google OAuth implementations include:
|
|
724
|
+
|
|
725
|
+
- **CSRF Protection**: State parameter validation to prevent cross-site request forgery
|
|
726
|
+
- **Session Security**: OAuth state tokens stored in session and validated on callback
|
|
727
|
+
- **Rate Limiting**: 10 requests per 5 minutes to prevent abuse
|
|
728
|
+
- **Token Validation**: Proper handling of expired or invalid OAuth tokens
|
|
729
|
+
- **Redirect Validation**: Only allows relative URLs to prevent open redirect attacks
|
|
730
|
+
- **Account Linking**: Users must pre-link OAuth accounts before login
|
|
731
|
+
- **2FA Integration**: Respects 2FA settings and trusted device configuration
|
|
732
|
+
- **Comprehensive Error Handling**: User-friendly error messages for all failure scenarios
|
|
733
|
+
|
|
734
|
+
---
|
|
735
|
+
|
|
586
736
|
## Middleware Reference
|
|
587
737
|
|
|
588
738
|
### `validateSession`
|
|
@@ -710,64 +860,6 @@ Authorization: your-secret-token
|
|
|
710
860
|
|
|
711
861
|
---
|
|
712
862
|
|
|
713
|
-
### `authapi(requiredRole)`
|
|
714
|
-
|
|
715
|
-
Advanced API authentication with role-based access control.
|
|
716
|
-
|
|
717
|
-
**Parameters:**
|
|
718
|
-
- `requiredRole` (array, optional) - Array of allowed roles
|
|
719
|
-
|
|
720
|
-
**Usage:**
|
|
721
|
-
```javascript
|
|
722
|
-
import { authapi } from 'mbkauthe';
|
|
723
|
-
|
|
724
|
-
// Any authenticated API user
|
|
725
|
-
app.get('/api/data', authapi(), (req, res) => {
|
|
726
|
-
console.log(req.user); // { username, UserName, role, Role }
|
|
727
|
-
res.json({ data: 'API data' });
|
|
728
|
-
});
|
|
729
|
-
|
|
730
|
-
// Only SuperAdmin via API
|
|
731
|
-
app.post('/api/admin/action', authapi(['SuperAdmin']), (req, res) => {
|
|
732
|
-
res.json({ success: true });
|
|
733
|
-
});
|
|
734
|
-
```
|
|
735
|
-
|
|
736
|
-
**Headers Required:**
|
|
737
|
-
```
|
|
738
|
-
Authorization: user-api-key-64-char-hex
|
|
739
|
-
```
|
|
740
|
-
|
|
741
|
-
**Behavior:**
|
|
742
|
-
- Validates API key from `Authorization` header
|
|
743
|
-
- Looks up user associated with API key
|
|
744
|
-
- Checks if user account is active
|
|
745
|
-
- Verifies user role if `requiredRole` is specified
|
|
746
|
-
- Blocks demo users from accessing endpoints
|
|
747
|
-
- Populates `req.user` with user information
|
|
748
|
-
- Returns 401 if unauthorized, 403 if insufficient permissions
|
|
749
|
-
|
|
750
|
-
**req.user Object:**
|
|
751
|
-
```javascript
|
|
752
|
-
req.user = {
|
|
753
|
-
username: "john.doe",
|
|
754
|
-
UserName: "john.doe",
|
|
755
|
-
role: "NormalUser",
|
|
756
|
-
Role: "NormalUser"
|
|
757
|
-
}
|
|
758
|
-
```
|
|
759
|
-
|
|
760
|
-
**Database Requirement:**
|
|
761
|
-
Requires `UserAuthApiKey` table:
|
|
762
|
-
```sql
|
|
763
|
-
CREATE TABLE "UserAuthApiKey" (
|
|
764
|
-
username VARCHAR(50) PRIMARY KEY REFERENCES "Users"("UserName"),
|
|
765
|
-
"key" VARCHAR(64) UNIQUE NOT NULL
|
|
766
|
-
);
|
|
767
|
-
```
|
|
768
|
-
|
|
769
|
-
---
|
|
770
|
-
|
|
771
863
|
## Error Codes
|
|
772
864
|
|
|
773
865
|
### HTTP Status Codes
|
|
@@ -876,7 +968,7 @@ app.get('/moderator',
|
|
|
876
968
|
### API Authentication
|
|
877
969
|
|
|
878
970
|
```javascript
|
|
879
|
-
import { authenticate
|
|
971
|
+
import { authenticate } from 'mbkauthe';
|
|
880
972
|
|
|
881
973
|
// Simple token authentication
|
|
882
974
|
app.post('/api/webhook',
|
|
@@ -887,24 +979,27 @@ app.post('/api/webhook',
|
|
|
887
979
|
}
|
|
888
980
|
);
|
|
889
981
|
|
|
890
|
-
// API
|
|
891
|
-
app.
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
// Fetch user profile
|
|
895
|
-
const profile = await getUserProfile(username);
|
|
896
|
-
|
|
897
|
-
res.json({ success: true, profile });
|
|
898
|
-
});
|
|
899
|
-
|
|
900
|
-
// API key with role requirement
|
|
901
|
-
app.delete('/api/admin/users/:id',
|
|
902
|
-
authapi(['SuperAdmin']),
|
|
982
|
+
// Admin API with token authentication
|
|
983
|
+
app.post('/api/admin/terminate-sessions',
|
|
984
|
+
authenticate(process.env.MAIN_SECRET_TOKEN),
|
|
903
985
|
async (req, res) => {
|
|
904
|
-
|
|
986
|
+
// Terminate all sessions
|
|
905
987
|
res.json({ success: true });
|
|
906
988
|
}
|
|
907
989
|
);
|
|
990
|
+
|
|
991
|
+
// Protected API endpoint (requires session)
|
|
992
|
+
app.get('/api/user/profile',
|
|
993
|
+
validateSession,
|
|
994
|
+
async (req, res) => {
|
|
995
|
+
const { username } = req.session.user;
|
|
996
|
+
|
|
997
|
+
// Fetch user profile
|
|
998
|
+
const profile = await getUserProfile(username);
|
|
999
|
+
|
|
1000
|
+
res.json({ success: true, profile });
|
|
1001
|
+
}
|
|
1002
|
+
);
|
|
908
1003
|
```
|
|
909
1004
|
|
|
910
1005
|
---
|