mbkauthe 5.0.0 → 5.0.2

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.
@@ -0,0 +1,251 @@
1
+ # Code Examples
2
+
3
+ [Back to API index](../api.md) | [Back to docs index](../../README.md) | [Back to project README](../../../README.md)
4
+
5
+ ## Code Examples
6
+
7
+ ### Basic Integration
8
+
9
+ ```javascript
10
+ import express from 'express';
11
+ import mbkauthe, { validateSession } from 'mbkauthe';
12
+ import dotenv from 'dotenv';
13
+
14
+ dotenv.config();
15
+
16
+ // Configure MBKAuthe
17
+ process.env.mbkautheVar = JSON.stringify({
18
+ APP_NAME: process.env.APP_NAME,
19
+ SESSION_SECRET_KEY: process.env.SESSION_SECRET_KEY,
20
+ IS_DEPLOYED: process.env.IS_DEPLOYED,
21
+ DOMAIN: process.env.DOMAIN,
22
+ LOGIN_DB: process.env.LOGIN_DB,
23
+ MBKAUTH_TWO_FA_ENABLE: process.env.MBKAUTH_TWO_FA_ENABLE,
24
+ COOKIE_EXPIRE_TIME: process.env.COOKIE_EXPIRE_TIME || 2,
25
+ loginRedirectURL: '/dashboard'
26
+ });
27
+
28
+ const app = express();
29
+
30
+ // Mount MBKAuthe routes
31
+ app.use(mbkauthe);
32
+
33
+ // Protected route
34
+ app.get('/dashboard', sessVal, (req, res) => {
35
+ res.send(`Welcome ${req.session.user.username}!`);
36
+ });
37
+
38
+ app.listen(3000, () => {
39
+ console.log('Server running on http://localhost:3000');
40
+ });
41
+ ```
42
+
43
+ ---
44
+
45
+ ### Role-Based Access Control
46
+
47
+ ```javascript
48
+ import { sessVal, roleChk, sessRole } from 'mbkauthe';
49
+
50
+ // Method 1: Separate middleware
51
+ app.get('/admin', sessVal, roleChk('SuperAdmin'), (req, res) => {
52
+ res.send('Admin panel');
53
+ }
54
+ );
55
+
56
+ // Method 2: Combined middleware
57
+ app.get('/admin', sessRole('SuperAdmin'), (req, res) => {
58
+ res.send('Admin panel');
59
+ }
60
+ );
61
+
62
+ // Allow any role except Guest
63
+ app.get('/content', sessVal, roleChk('Any', 'Guest'), (req, res) => {
64
+ res.send('Content for registered users');
65
+ }
66
+ );
67
+
68
+ // Multiple roles (using separate middleware)
69
+ app.get('/moderator', sessVal, (req, res, next) => {
70
+ if (['SuperAdmin', 'NormalUser'].includes(req.session.user.role)) {
71
+ next();
72
+ } else {
73
+ res.status(403).send('Access denied');
74
+ }
75
+ },
76
+ (req, res) => {
77
+ res.send('Moderator panel');
78
+ }
79
+ );
80
+ ```
81
+
82
+ ---
83
+
84
+ ### API Authentication
85
+
86
+ ```javascript
87
+ import { authenticate } from 'mbkauthe';
88
+
89
+ // Simple token authentication
90
+ app.post('/api/webhook', authenticate(process.env.WEBHOOK_SECRET), (req, res) => {
91
+ // Process webhook
92
+ res.json({ received: true });
93
+ }
94
+ );
95
+
96
+ // Admin API with token authentication
97
+ app.post('/api/admin/terminate-sessions', authenticate(process.env.MAIN_SECRET_TOKEN), async (req, res) => {
98
+ // Terminate all sessions
99
+ res.json({ success: true });
100
+ }
101
+ );
102
+
103
+ // Protected API endpoint (requires session)
104
+ app.get('/api/user/profile', sessVal, async (req, res) => {
105
+ const { username } = req.session.user;
106
+
107
+ // Fetch user profile
108
+ const profile = await getUserProfile(username);
109
+
110
+ res.json({ success: true, profile });
111
+ }
112
+ );
113
+ ```
114
+
115
+ ---
116
+
117
+ ### Client-Side Login
118
+
119
+ ```javascript
120
+ // Login form submission
121
+ document.getElementById('loginForm').addEventListener('submit', async (e) => {
122
+ e.preventDefault();
123
+
124
+ const username = document.getElementById('username').value;
125
+ const password = document.getElementById('password').value;
126
+
127
+ try {
128
+ const response = await fetch('/mbkauthe/api/login', {
129
+ method: 'POST',
130
+ headers: {
131
+ 'Content-Type': 'application/json',
132
+ },
133
+ body: JSON.stringify({ username, password })
134
+ });
135
+
136
+ const data = await response.json();
137
+
138
+ if (data.success) {
139
+ if (data.twoFactorRequired) {
140
+ // Redirect to 2FA page
141
+ window.location.href = '/mbkauthe/2fa';
142
+ } else {
143
+ // Login successful, redirect
144
+ window.location.href = data.redirectUrl || '/dashboard';
145
+ }
146
+ } else {
147
+ alert(data.message || 'Login failed');
148
+ }
149
+ } catch (error) {
150
+ console.error('Login error:', error);
151
+ alert('An error occurred during login');
152
+ }
153
+ });
154
+ ```
155
+
156
+ ---
157
+
158
+ ### Client-Side Logout
159
+
160
+ ```javascript
161
+ async function logout() {
162
+ // Get CSRF token from page
163
+ const csrfToken = document.querySelector('[name="_csrf"]').value;
164
+
165
+ try {
166
+ const response = await fetch('/mbkauthe/api/logout', {
167
+ method: 'POST',
168
+ headers: {
169
+ 'Content-Type': 'application/json',
170
+ },
171
+ body: JSON.stringify({ _csrf: csrfToken })
172
+ });
173
+
174
+ const data = await response.json();
175
+
176
+ if (data.success) {
177
+ window.location.href = '/mbkauthe/login';
178
+ } else {
179
+ alert('Logout failed: ' + data.message);
180
+ }
181
+ } catch (error) {
182
+ console.error('Logout error:', error);
183
+ }
184
+ }
185
+ ```
186
+
187
+ ---
188
+
189
+ ### Database Access
190
+
191
+ ```javascript
192
+ import { dblogin } from 'mbkauthe';
193
+
194
+ // Custom query using the database pool
195
+ app.get('/api/users', sessVal, roleChk('SuperAdmin'), async (req, res) => {
196
+ try {
197
+ const result = await dblogin.query(
198
+ 'SELECT id, "UserName", "Role", "Active" FROM "Users" ORDER BY id'
199
+ );
200
+
201
+ res.json({
202
+ success: true,
203
+ users: result.rows
204
+ });
205
+ } catch (error) {
206
+ console.error('Database error:', error);
207
+ res.status(500).json({
208
+ success: false,
209
+ message: 'Internal Server Error'
210
+ });
211
+ }
212
+ });
213
+ ```
214
+
215
+ ---
216
+
217
+ ### Error Handling
218
+
219
+ ```javascript
220
+ // Custom error handler
221
+ app.use((err, req, res, next) => {
222
+ console.error('Error:', err);
223
+
224
+ if (err.code === 'EBADCSRFTOKEN') {
225
+ return res.status(403).json({
226
+ success: false,
227
+ message: 'Invalid CSRF token'
228
+ });
229
+ }
230
+
231
+ res.status(500).json({
232
+ success: false,
233
+ message: 'Internal Server Error'
234
+ });
235
+ });
236
+
237
+ // 404 handler
238
+ app.use((req, res) => {
239
+ res.status(404).render('Error/dError.handlebars', {
240
+ layout: false,
241
+ code: 404,
242
+ error: 'Not Found',
243
+ message: 'The requested page was not found.',
244
+ pagename: 'Home',
245
+ page: '/',
246
+ });
247
+ });
248
+ ```
249
+
250
+ ---
251
+
@@ -0,0 +1,239 @@
1
+ # Middleware
2
+
3
+ [Back to API index](../api.md) | [Back to docs index](../../README.md) | [Back to project README](../../../README.md)
4
+
5
+ ## Middleware Reference
6
+
7
+ ### `validateSession`/`sessRole`
8
+
9
+ Validates that the user has an active session.
10
+
11
+ **Usage:**
12
+ ```javascript
13
+ import { sessRole } from 'mbkauthe';
14
+
15
+ app.get('/protected', sessRole, (req, res) => {
16
+ // User is authenticated
17
+ const user = req.session.user;
18
+ // user contains: { id, username, UserName, role, Role, sessionId }
19
+ res.send(`Welcome ${user.username}!`);
20
+ });
21
+ ```
22
+
23
+ **Behavior:**
24
+ - Checks for active session in `req.session.user`
25
+ - Attempts to restore session from `sessionId` cookie if session not found
26
+ - Validates session against database
27
+ - Checks if user account is still active
28
+ - Verifies user is authorized for the current application
29
+ - Redirects to login page if validation fails
30
+
31
+ **JSON vs HTML error responses:**
32
+
33
+ When `validateSession` fails, MBKAuthe will either render an HTML error/login page (browser flow) or return a JSON error response (API/AJAX flow). A request is treated as **JSON** when any of these are true:
34
+
35
+ - URL/path starts with `/mbkauthe/api/` or `/api/`
36
+ - `X-Requested-With: XMLHttpRequest`
37
+ - `Accept` indicates JSON (e.g., `application/json`) and does not explicitly prefer `text/html`
38
+ - `User-Agent` matches a non-browser client (e.g., `curl`, `wget`, `Postman`, `Insomnia`)
39
+ - `User-Agent: json` (explicitly forces JSON responses)
40
+
41
+ **Example (force JSON errors on a page route):**
42
+ ```bash
43
+ curl -i -H "User-Agent: json" http://localhost:3000/mbkauthe/test
44
+ ```
45
+
46
+ ### reloadSessionUser(req, res)
47
+
48
+ Use this helper when you need to refresh the values stored in `req.session.user` from the authoritative database record (for example, after a profile update that changes FullName, or when session expiration policies are updated).
49
+
50
+ - Behavior:
51
+ - Validates the session against the database (sessionId, active)
52
+ - Updates `req.session.user` fields: `username`, `role`, `allowedApps`, `fullname`
53
+ - Uses cached `fullName` cookie if available; falls back to querying `profiledata`
54
+ - Syncs `username`, `fullName`, and `sessionId` cookies for client display
55
+ - If the session is invalid (sessionId mismatch, inactive account, or unauthorized), it destroys the session and clears cookies
56
+
57
+ - Returns: `Promise<boolean>` — `true` if session was refreshed and still valid, `false` if session was invalidated or reload failed.
58
+
59
+ - Example:
60
+ ```javascript
61
+ import { reloadSessionUser } from 'mbkauthe';
62
+
63
+ // After updating profile data
64
+ app.post('/mbkauthe/api/update-profile', sessRole, async (req, res) => {
65
+ // ... update profiledata.FullName in DB ...
66
+ const refreshed = await reloadSessionUser(req, res);
67
+ if (!refreshed) {
68
+ return res.status(401).json({ success: false, message: 'Session invalidated' });
69
+ }
70
+ res.json({ success: true, fullname: req.session.user.fullname });
71
+ });
72
+ ```
73
+
74
+ **Session Object:**
75
+ ```javascript
76
+ req.session.user = {
77
+ id: 1, // User ID
78
+ username: "john.doe", // Username (login name)
79
+ fullname: "John Doe", // Optional display name fetched from profiledata
80
+ role: "NormalUser", // User role
81
+ sessionId: "abc123...", // 64-char hex session ID
82
+ }
83
+ ```
84
+
85
+ **Session Cookie Sync:**
86
+ - The middleware sets non-httpOnly cookies for client display:
87
+ - `username` — the login username (exposed for UI)
88
+ - `fullName` — the display name (falls back to username if not available)
89
+
90
+ These cookies allow front-end UI to display a friendly name without making extra requests to the server.
91
+ ---
92
+
93
+ ### `checkRolePermission(requiredRole, notAllowed)`/`roleChk `
94
+
95
+ Checks if the authenticated user has the required role.
96
+
97
+ **Parameters:**
98
+ - `requiredRole` (string) - Required role: `"SuperAdmin"`, `"NormalUser"`, `"Guest"`, `"member"`, or `"Any"`/`"any"`
99
+ - `notAllowed` (string, optional) - Role that is explicitly not allowed
100
+
101
+ **Usage:**
102
+ ```javascript
103
+ import { sessVal, roleChk } from 'mbkauthe';
104
+
105
+ // Only SuperAdmin can access
106
+ app.get('/admin', sessVal, roleChk('SuperAdmin'), (req, res) => {
107
+ res.send('Admin panel');
108
+ });
109
+
110
+ // Any authenticated user except Guest
111
+ app.get('/content', sessVal, roleChk('Any', 'Guest'), (req, res) => {
112
+ res.send('Protected content');
113
+ });
114
+ ```
115
+
116
+ **Behavior:**
117
+ - Checks if user is authenticated first
118
+ - Fetches user role from database
119
+ - Returns 403 if user has `notAllowed` role
120
+ - Returns 403 if user doesn't have `requiredRole` (unless role is "Any")
121
+ - Calls `next()` if authorized
122
+
123
+ ---
124
+
125
+ ### `validateSessionAndRole(requiredRole, notAllowed)`/`sessRole`
126
+
127
+ Combined middleware for session validation and role checking.
128
+
129
+ **Parameters:**
130
+ - `requiredRole` (string) - Required role
131
+ - `notAllowed` (string, optional) - Role that is explicitly not allowed
132
+
133
+ **Usage:**
134
+ ```javascript
135
+ import { sessRole, roleChk } from 'mbkauthe';
136
+
137
+ // Validate session AND check role in one middleware
138
+ app.get('/moderator', sessRole('SuperAdmin'), (req, res) => {
139
+ res.send('Moderator panel');
140
+ });
141
+ ```
142
+
143
+ **Equivalent to:**
144
+ ```javascript
145
+ app.get('/moderator', sessVal, roleChk('SuperAdmin'), (req, res) => {
146
+ res.send('Moderator panel');
147
+ });
148
+ ```
149
+
150
+ ---
151
+
152
+ ### Strict validation helpers
153
+
154
+ For endpoints that must reject API token-based authentication and only accept browser session cookies, MBKAuthe exposes two strict helpers:
155
+
156
+ - `strictValidateSession`/`strictSessVal` — same as `validateSession`, but rejects requests that provide `Authorization` headers (API tokens) and returns `401` when a token is used.
157
+ - `strictValidateSessionAndRole(requiredRole, notAllowed)`/`strictSessRole` — combined helper that behaves like `validateSessionAndRole` but enforces strict (cookie-only) authentication.
158
+
159
+ **Usage examples:**
160
+ ```javascript
161
+ import { strictSessVal, strictSessRole } from 'mbkauthe';
162
+
163
+ // Accept only cookie sessions
164
+ app.get('/sensitive', strictSessVal, (req, res) => {
165
+ res.send('Sensitive data');
166
+ });
167
+
168
+ // Validate session AND role, using cookie-only authentication
169
+ app.get('/admin', strictSessRole('SuperAdmin'), (req, res) => {
170
+ res.send('Admin');
171
+ });
172
+ ```
173
+
174
+ ---
175
+
176
+ ### Response Utilities
177
+
178
+ MBKAuthe exports small helpers to assist with page rendering and context:
179
+
180
+ - `getUserContext(req)` — returns a lightweight context object for templates: `{ userLoggedIn, isuserlogin, username, fullname, role, allowedApps }`.
181
+ - `renderPage(req, res, fileLocation, layout = true, data = {})` — renders a template with the user/context merged into the data; returns a Promise and yields the typical Express `res.render` behavior.
182
+ - `renderError(res, req, options)` — renders the standardized error page; note the signature is `(res, req, options)` and `options` follow the `ErrorRenderOptions` described in the types.
183
+
184
+ **Example:**
185
+
186
+ ```javascript
187
+ import { getUserContext, renderPage, renderError } from 'mbkauthe';
188
+
189
+ app.get('/dashboard', (req, res) => {
190
+ const ctx = getUserContext(req);
191
+ return renderPage(req, res, 'info', true, { greeting: 'Hello', ...ctx });
192
+ });
193
+
194
+ app.get('/err', (req, res) => {
195
+ return renderError(res, req, {
196
+ layout: false,
197
+ code: 500,
198
+ error: "Internal Server Error",
199
+ message: "Simulated 500 Error",
200
+ details: "This is a simulated 500 error page for testing purposes.",
201
+ pagename: "Home",
202
+ page: "/mbkauthe/login",
203
+ });
204
+ });
205
+ ```
206
+
207
+ ---
208
+
209
+ ### `authenticate(token)`
210
+
211
+ API authentication middleware for server-to-server communication.
212
+
213
+ **Parameters:**
214
+ - `token` (string) - Secret token for authentication
215
+
216
+ **Usage:**
217
+ ```javascript
218
+ import { authenticate } from 'mbkauthe';
219
+
220
+ app.post('/api/data', authenticate(process.env.API_TOKEN), (req, res) => {
221
+ res.json({ data: 'Protected API data' });
222
+ });
223
+ ```
224
+
225
+ **Headers Required:**
226
+ ```
227
+ Authorization: Bearer your-secret-token
228
+ ```
229
+
230
+ You can also send the raw token without the `Bearer` prefix.
231
+
232
+ **Behavior:**
233
+ - Checks `Authorization` header
234
+ - Extracts the token (strips optional `Bearer` prefix)
235
+ - Compares the provided token to the expected token using a timing-safe SHA-256 hash comparison
236
+ - Returns 401 if token doesn't match
237
+
238
+ ---
239
+
@@ -0,0 +1,52 @@
1
+ # Operational Reference
2
+
3
+ [Back to API index](../api.md) | [Back to docs index](../../README.md) | [Back to project README](../../../README.md)
4
+
5
+ ## Error Codes
6
+
7
+ ### HTTP Status Codes
8
+
9
+ | Code | Meaning | Usage |
10
+ |------|---------|-------|
11
+ | 200 | OK | Successful request |
12
+ | 400 | Bad Request | Invalid input data |
13
+ | 401 | Unauthorized | Authentication required or failed |
14
+ | 403 | Forbidden | Insufficient permissions |
15
+ | 404 | Not Found | Resource not found |
16
+ | 429 | Too Many Requests | Rate limit exceeded |
17
+ | 500 | Internal Server Error | Server-side error |
18
+
19
+ ---
20
+
21
+ ## Security Best Practices
22
+
23
+ 1. **Always use HTTPS in production** - Set `IS_DEPLOYED=true` and ensure your server uses SSL/TLS
24
+ 2. **Keep SESSION_SECRET_KEY secure** - Use a strong, randomly generated key
25
+ 3. **Enable 2FA for sensitive applications** - Set `MBKAUTH_TWO_FA_ENABLE=true`
26
+ 4. **Validate all user input** - Never trust client-side data
27
+ 5. **Use rate limiting** - Already implemented for authentication endpoints
28
+ 6. **Keep dependencies updated** - Regularly update npm packages
29
+ 7. **Monitor for security vulnerabilities** - Use `npm audit`
30
+ 8. **Use prepared statements** - Prevent SQL injection (already implemented)
31
+ 9. **Implement proper logging** - Track authentication events
32
+ 10. **Regular security audits** - Review code and configurations
33
+
34
+ ---
35
+
36
+ ## Rate Limits
37
+
38
+ | Endpoint | Limit | Window |
39
+ |----------|-------|--------|
40
+ | `/mbkauthe/api/login` | 8 requests | 1 minute |
41
+ | `/mbkauthe/api/logout` | 10 requests | 1 minute |
42
+ | `/mbkauthe/api/verify-2fa` | 5 requests | 1 minute |
43
+ | `/mbkauthe/api/github/login` | 10 requests | 5 minutes |
44
+ | `/mbkauthe/api/github/login/callback` | 10 requests | 5 minutes |
45
+ | `/mbkauthe/login` | 8 requests | 1 minute |
46
+ | `/mbkauthe/info` | 8 requests | 1 minute |
47
+ | `/mbkauthe/test` | 8 requests | 1 minute |
48
+
49
+ Rate limits are applied per IP address. Logged-in users are exempt from some rate limits (e.g., login page rate limit).
50
+
51
+ ---
52
+
@@ -0,0 +1,19 @@
1
+ # API Reference
2
+
3
+ [Back to docs index](../README.md) | [Back to project README](../../README.md)
4
+
5
+ The API reference is split by responsibility so each source file stays focused and easy to review.
6
+
7
+ ## Sections
8
+
9
+ - [Authentication and sessions](api/authentication.md) - session cookies, API tokens, and session lifetime.
10
+ - [Endpoints](api/endpoints.md) - public routes, protected routes, multi-account routes, information routes, diagnostics, and OAuth routes.
11
+ - [Middleware](api/middleware.md) - `sessVal`, `roleChk`, strict session helpers, render helpers, and token authentication.
12
+ - [Code examples](api/examples.md) - Express integration, role checks, API auth, client login/logout, database access, and error handling.
13
+ - [Operational reference](api/operations.md) - HTTP status codes, security best practices, and rate limits.
14
+
15
+ ## Related Reference
16
+
17
+ - [Error codes](error-codes.md)
18
+ - [Database guide](../guides/database.md)
19
+ - [Configuration guide](../guides/configuration.md)
@@ -1,5 +1,7 @@
1
1
  # Error Messages & Codes
2
2
 
3
+ [Back to docs index](../README.md) | [Back to project README](../../README.md)
4
+
3
5
  MBKAuthe provides a comprehensive error messaging system with standardized error codes and user-friendly messages.
4
6
 
5
7
  ## Overview
@@ -12,7 +12,7 @@ async function main() {
12
12
 
13
13
  console.log("[mbkauthe] Starting schema creation...");
14
14
 
15
- const schemaPath = path.resolve(__dirname, "../docs/db.sql");
15
+ const schemaPath = path.resolve(__dirname, "../docs/schema/db.sql");
16
16
 
17
17
  console.log(`[mbkauthe] Schema file: ${schemaPath}`);
18
18
 
@@ -118,4 +118,4 @@ async function main() {
118
118
  }
119
119
  }
120
120
 
121
- main();
121
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mbkauthe",
3
- "version": "5.0.0",
3
+ "version": "5.0.2",
4
4
  "description": "MBKTech's reusable authentication system for Node.js applications.",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -10,8 +10,8 @@
10
10
  "create-tables": "node lib/createTable.js",
11
11
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
12
12
  "test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch",
13
- "render:mermaid": "npx @mermaid-js/mermaid-cli -i docs/auth-flows.mmd -o docs/images/auth-flows.svg",
14
- "render:mermaid:png": "npx @mermaid-js/mermaid-cli -i docs/auth-flows.mmd -o docs/images/auth-flows.png -s 20"
13
+ "render:mermaid": "npx @mermaid-js/mermaid-cli -i docs/diagrams/auth-flows.mmd -o docs/images/auth-flows.svg",
14
+ "render:mermaid:png": "npx @mermaid-js/mermaid-cli -i docs/diagrams/auth-flows.mmd -o docs/images/auth-flows.png -s 20"
15
15
  },
16
16
  "imports": {
17
17
  "#pool.js": "./lib/pool.js",
@@ -53,6 +53,7 @@
53
53
  "registry": "https://registry.npmjs.org/"
54
54
  },
55
55
  "dependencies": {
56
+ "@mermaid-js/mermaid-cli": "^11.15.0",
56
57
  "bytes": "^3.1.2",
57
58
  "connect-pg-simple": "^10.0.0",
58
59
  "content-type": "^1.0.5",
@@ -1,71 +0,0 @@
1
- sequenceDiagram
2
- participant C as Client
3
- participant S as Server
4
- participant DB as Database
5
-
6
- rect rgb(235, 245, 255)
7
- Note over C, DB: Authentication Flow
8
-
9
- C->>S: POST /login (username, password)
10
- S->>S: Validate payload format
11
- S->>DB: Query User & 2FA status
12
- DB-->>S: User Data (Password Hash, 2FA Enabled)
13
- S->>S: Compare Hash (PasswordEnc)
14
-
15
- alt 2FA Enabled & Device Not Trusted
16
- S-->>C: 200 (twoFactorRequired: true)
17
-
18
- C->>S: POST /verify-2fa (TOTP Token)
19
- S->>DB: Fetch TOTP Secret
20
- DB-->>S: Secret Key
21
- S->>S: Verify TOTP
22
- end
23
-
24
- Note over S, DB: completeLoginProcess
25
-
26
- S->>DB: Delete old sessions & Prune max sessions
27
- S->>S: Regenerate Session ID
28
- S->>DB: Insert new Session row
29
- S->>DB: Update Users.last_login
30
-
31
- S-->>C: 200 Success (Set Encrypted Cookies)
32
- end
33
-
34
- rect rgb(245, 245, 245)
35
- Note over C, DB: Request Authentication Middleware Flow
36
-
37
- C->>S: Request + Auth (Cookie or Bearer Token)
38
-
39
- rect rgb(240, 240, 240)
40
- Note over S, DB: Token Path (API)
41
-
42
- alt Header: Bearer mbk_token
43
- S->>S: Hash Token
44
- S->>DB: Query ApiTokens JOIN Users
45
-
46
- alt Valid & Not Expired
47
- S->>DB: Update last_used
48
- S->>S: Authorize Scope
49
- else Invalid/Expired
50
- S-->>C: 401 Unauthorized
51
- end
52
- end
53
- end
54
-
55
- rect rgb(220, 230, 250)
56
- Note over S, DB: Session Path (Web)
57
-
58
- alt Cookie: sessionId exists
59
- S->>DB: Query Sessions JOIN Users
60
- DB-->>S: Session Data + User Status
61
-
62
- alt Session Valid & User Active
63
- S->>S: Sync Cookies & Update session.user
64
- S->>S: Proceed to Route
65
- else Session Expired/User Inactive
66
- S->>S: Destroy Session & Clear Cookies
67
- S-->>C: 403 Forbidden
68
- end
69
- end
70
- end
71
- end