mbkauthe 1.0.4 → 1.0.5
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 +121 -1
- package/docs/db.md +90 -0
- package/env.md +55 -0
- package/lib/main.js +37 -51
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1 +1,121 @@
|
|
|
1
|
-
# mbkauthe
|
|
1
|
+
# mbkauthe
|
|
2
|
+
|
|
3
|
+
[](https://github.com/MIbnEKhalid/mbkauthe/actions/workflows/publish.yml) [](https://github.com/MIbnEKhalid/mbkauthe/actions/workflows/codeql.yml)
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Introduction](#mbkauth)
|
|
8
|
+
- [Features](#features)
|
|
9
|
+
- [Installation](#installation)
|
|
10
|
+
- [Usage](#usage)
|
|
11
|
+
- [Basic Setup](#basic-setup)
|
|
12
|
+
- [API Endpoints](#api-endpoints)
|
|
13
|
+
- [Login](#login)
|
|
14
|
+
- [Logout](#logout)
|
|
15
|
+
- [Terminate All Sessions](#terminate-all-sessions)
|
|
16
|
+
- [Database Structure](#database-structure)
|
|
17
|
+
- [License](#license)
|
|
18
|
+
- [Contact & Support](#contact--support)
|
|
19
|
+
|
|
20
|
+
`mbkAuthe` is a reusable authentication system for Node.js applications, designed to simplify session management, user authentication, and role-based access control. It integrates seamlessly with PostgreSQL and supports features like Two-Factor Authentication (2FA), session restoration, and reCAPTCHA verification.
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- **Session Management**: Secure session handling using `express-session` and `connect-pg-simple`.
|
|
25
|
+
- **Role-Based Access Control**: Validate user roles and permissions with ease.
|
|
26
|
+
- **Two-Factor Authentication (2FA)**: Optional 2FA support for enhanced security.
|
|
27
|
+
- **reCAPTCHA Integration**: Protect login endpoints with Google reCAPTCHA.
|
|
28
|
+
- **Cookie Management**: Configurable cookie expiration and domain settings.
|
|
29
|
+
- **PostgreSQL Integration**: Uses a connection pool for efficient database interactions.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
Install the package via npm:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install mbkauthe
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
### Basic Setup
|
|
41
|
+
1. Import and configure the router in your Express application:
|
|
42
|
+
```javascript
|
|
43
|
+
import express from "express";
|
|
44
|
+
import mbkAuthRouter from "mbkauthe";
|
|
45
|
+
|
|
46
|
+
const app = express();
|
|
47
|
+
|
|
48
|
+
app.use(mbkAuthRouter);
|
|
49
|
+
|
|
50
|
+
app.listen(3000, () => {
|
|
51
|
+
console.log("Server is running on port 3000");
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
2. Ensure your ``.env` file is properly configured. Refer to the [Configuration Guide(env.md)](env.md) for details.
|
|
55
|
+
|
|
56
|
+
Example `.env` file:
|
|
57
|
+
```code
|
|
58
|
+
RECAPTCHA_SECRET_KEY=your-recaptcha-secret-key
|
|
59
|
+
SESSION_SECRET_KEY=your-session-secret-key
|
|
60
|
+
LOGIN_DB=postgres://username:password@host:port/database
|
|
61
|
+
DOMAIN=yourdomain.com
|
|
62
|
+
IS_DEPLOYED=true
|
|
63
|
+
MBKAUTH_TWO_FA_ENABLE=false
|
|
64
|
+
COOKIE_EXPIRE_TIME=2
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## API Endpoints
|
|
68
|
+
|
|
69
|
+
### Login
|
|
70
|
+
|
|
71
|
+
**POST** `/mbkauth/api/login`
|
|
72
|
+
- Request Body:
|
|
73
|
+
- `username`: User's username.
|
|
74
|
+
- `password`: User's password.
|
|
75
|
+
- `token`: (Optional) 2FA token.
|
|
76
|
+
- `recaptcha`: reCAPTCHA response.
|
|
77
|
+
|
|
78
|
+
- Response:
|
|
79
|
+
- `200`: Login successful.
|
|
80
|
+
- `400`: Missing or invalid input.
|
|
81
|
+
- `401`: Unauthorized (e.g., invalid credentials or 2FA token).
|
|
82
|
+
- `500`: Internal server error.
|
|
83
|
+
|
|
84
|
+
### Logout
|
|
85
|
+
|
|
86
|
+
**POST** `/mbkauth/api/logout`
|
|
87
|
+
- Response:
|
|
88
|
+
- `200`: Login successful.
|
|
89
|
+
- `400`: User not logged in.
|
|
90
|
+
- `500`: Internal server error.
|
|
91
|
+
|
|
92
|
+
### Terminate All Sessions
|
|
93
|
+
|
|
94
|
+
**POST** `/mbkauth/api/terminateAllSessions`
|
|
95
|
+
- Authentication: Requires a valid `Main_SECRET_TOKEN` in the `Authorization` header.
|
|
96
|
+
- Response:
|
|
97
|
+
- `200`: All sessions terminated successfully.
|
|
98
|
+
- `500`: Internal server error.
|
|
99
|
+
-
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
## Database Structure
|
|
103
|
+
|
|
104
|
+
This project utilizes three primary tables:
|
|
105
|
+
|
|
106
|
+
1. **User**: Stores the main user information.
|
|
107
|
+
2. **sess**: Contains session-related data for users.
|
|
108
|
+
3. **TwoFA**: Saves the Two-Factor Authentication (2FA) secrets for users.
|
|
109
|
+
|
|
110
|
+
For detailed information about table columns, schema, and queries to create these tables, refer to the [Database Guide (docs/db.md)](docs/db.md).
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
This project is licensed under the `Mozilla Public License 2.0`. See the [LICENSE](./LICENSE) file for details.
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
## Contact & Support
|
|
118
|
+
|
|
119
|
+
For questions or contributions, please contact Muhammad Bin Khalid at [mbktechstudio.com/Support](https://mbktechstudio.com/Support/), [support@mbktechstudio.com](mailto:support@mbktechstudio.com) or [chmuhammadbinkhalid28.com](mailto:chmuhammadbinkhalid28.com).
|
|
120
|
+
|
|
121
|
+
**Developed by [Muhammad Bin Khalid](https://github.com/MIbnEKhalid)**
|
package/docs/db.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
## Database structure
|
|
2
|
+
|
|
3
|
+
[<- Back](README.md)
|
|
4
|
+
|
|
5
|
+
## Table of Contents
|
|
6
|
+
|
|
7
|
+
1. [Users Table](#users-table)
|
|
8
|
+
2. [Session Table](#session-table)
|
|
9
|
+
3. [Two-Factor Authentication Table](#two-factor-authentication-table)
|
|
10
|
+
4. [Query to Add a User](#query-to-add-a-user)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
### Users Table
|
|
14
|
+
|
|
15
|
+
- **Columns:**
|
|
16
|
+
|
|
17
|
+
- `id` (INTEGER, auto-increment, primary key): Unique identifier for each user.
|
|
18
|
+
- `UserName` (TEXT): The username of the user.
|
|
19
|
+
- `Password` (TEXT): The hashed password of the user.
|
|
20
|
+
- `Role` (ENUM): The role of the user. Possible values: `SuperAdmin`, `NormalUser`, `Guest`.
|
|
21
|
+
- `Active` (BOOLEAN): Indicates whether the user account is active.
|
|
22
|
+
- `HaveMailAccount` (BOOLEAN)(optional): Indicates if the user has a linked mail account.
|
|
23
|
+
- `SessionId` (TEXT): The session ID associated with the user.
|
|
24
|
+
- `GuestRole` (JSONB): Stores additional guest-specific role information in binary JSON format.
|
|
25
|
+
|
|
26
|
+
- **Schema:**
|
|
27
|
+
```sql
|
|
28
|
+
CREATE TABLE "Users" (
|
|
29
|
+
id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
|
|
30
|
+
"UserName" TEXT NOT NULL,
|
|
31
|
+
"Password" TEXT NOT NULL,
|
|
32
|
+
"Role" TEXT CHECK("Role" IN ('SuperAdmin', 'NormalUser', 'Guest')) NOT NULL DEFAULT 'NormalUser'::text,
|
|
33
|
+
"Active" BOOLEAN NOT NULL DEFAULT true,
|
|
34
|
+
"HaveMailAccount" BOOLEAN NOT NULL DEFAULT false,
|
|
35
|
+
"SessionId" TEXT,
|
|
36
|
+
"GuestRole" JSONB DEFAULT '{"allowPages": [""], "NotallowPages": [""]}'::jsonb
|
|
37
|
+
);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
### Session Table
|
|
41
|
+
|
|
42
|
+
- **Columns:**
|
|
43
|
+
|
|
44
|
+
- `sid` (VARCHAR, primary key): Unique session identifier.
|
|
45
|
+
- `sess` (JSON): Session data stored in JSON format.
|
|
46
|
+
- `expire` (TIMESTAMP): Expiration timestamp for the session.
|
|
47
|
+
|
|
48
|
+
- **Schema:**
|
|
49
|
+
```sql
|
|
50
|
+
CREATE TABLE session (
|
|
51
|
+
sid VARCHAR PRIMARY KEY,
|
|
52
|
+
sess JSON NOT NULL,
|
|
53
|
+
expire TIMESTAMP NOT NULL
|
|
54
|
+
);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Two-Factor Authentication Table
|
|
58
|
+
|
|
59
|
+
- **Columns:**
|
|
60
|
+
|
|
61
|
+
- `UserName` (TEXT): The username of the user.
|
|
62
|
+
- `TwoFAStatus` (TEXT): The status of two-factor authentication (e.g., enabled, disabled).
|
|
63
|
+
- `TwoFASecret` (TEXT): The secret key used for two-factor authentication.
|
|
64
|
+
|
|
65
|
+
- **Schema:**
|
|
66
|
+
```sql
|
|
67
|
+
CREATE TABLE "TwoFA" (
|
|
68
|
+
"UserName" TEXT NOT NULL PRIMARY KEY,
|
|
69
|
+
"TwoFAStatus" TEXT NOT NULL DEFAULT false,
|
|
70
|
+
"TwoFASecret" TEXT NOT NULL
|
|
71
|
+
);
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Query to Add a User
|
|
75
|
+
|
|
76
|
+
To add new users to the `Users` table, use the following SQL queries:
|
|
77
|
+
|
|
78
|
+
```sql
|
|
79
|
+
INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "SessionId", "GuestRole")
|
|
80
|
+
VALUES ('support', '12345678', 'SuperAdmin', true, false, NULL, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
|
|
81
|
+
|
|
82
|
+
INSERT INTO "Users" ("UserName", "Password", "Role", "Active", "HaveMailAccount", "SessionId", "GuestRole")
|
|
83
|
+
VALUES ('test', '12345678', 'NormalUser', true, false, NULL, '{"allowPages": [""], "NotallowPages": [""]}'::jsonb);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- Replace `support` and `test` with the desired usernames.
|
|
87
|
+
- Replace `12345678` with the actual passwords.
|
|
88
|
+
- Adjust the `Role` values as needed (`SuperAdmin`, `NormalUser`, or `Guest`).
|
|
89
|
+
- Modify the `Active` and `HaveMailAccount` values as required.
|
|
90
|
+
- Update the `GuestRole` JSON object if specific permissions are required(this functionality is under construction).
|
package/env.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Configuration Guide
|
|
2
|
+
|
|
3
|
+
[<- Back](README.md)
|
|
4
|
+
|
|
5
|
+
## reCAPTCHA Settings
|
|
6
|
+
```properties
|
|
7
|
+
RECAPTCHA_SECRET_KEY=123
|
|
8
|
+
```
|
|
9
|
+
> Note: Obtain your secret key from Google reCAPTCHA Admin Console.
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
## Session Settings
|
|
13
|
+
```properties
|
|
14
|
+
SESSION_SECRET_KEY=123
|
|
15
|
+
IS_DEPLOYED=true
|
|
16
|
+
DOMAIN=mbktechstudio.com
|
|
17
|
+
```
|
|
18
|
+
> **SESSION_SECRET_KEY**: Generate a secure key using [Generate Secret](https://generate-secret.vercel.app/32).
|
|
19
|
+
|
|
20
|
+
> **IS_DEPLOYED**:
|
|
21
|
+
|
|
22
|
+
> - `true`: For deployed environments. Sessions are shared across all subDOMAINs of `.mbktechstudio.com` or the DOMAIN specified in `DOMAIN`.
|
|
23
|
+
|
|
24
|
+
> - `false`: For local development.
|
|
25
|
+
|
|
26
|
+
> - Important: If set to `true`, login functionality will not work on `localhost`. Use a valid DOMAIN for proper operation.
|
|
27
|
+
|
|
28
|
+
> **DOMAIN**:
|
|
29
|
+
|
|
30
|
+
> - Set `DOMAIN` to your DOMAIN
|
|
31
|
+
|
|
32
|
+
> - If you don't have a DOMAIN, set `IS_DEPLOYED=false`.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
## Database Settings
|
|
36
|
+
|
|
37
|
+
```properties
|
|
38
|
+
LOGIN_DB=postgresql://username:password@server.DOMAIN/db_name
|
|
39
|
+
```
|
|
40
|
+
> Replace the placeholder with your PostgreSQL connection string.
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
## Two-Factor Authentication (2FA)
|
|
44
|
+
```properties
|
|
45
|
+
MBKAUTH_TWO_FA_ENABLE=false
|
|
46
|
+
```
|
|
47
|
+
> MBKAUTH_TWO_FA_ENABLE: Set to `true` to enable Two-Factor Authentication.
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
## Cookie Settings
|
|
51
|
+
|
|
52
|
+
```properties
|
|
53
|
+
COOKIE_EXPIRE_TIME=5
|
|
54
|
+
```
|
|
55
|
+
> Cookie expiration time in days. Default is `2 days`.
|
package/lib/main.js
CHANGED
|
@@ -20,25 +20,11 @@ try {
|
|
|
20
20
|
} else {
|
|
21
21
|
console.warn("Invalid COOKIE_EXPIRE_TIME in environment variables, using default value");
|
|
22
22
|
}
|
|
23
|
-
|
|
23
|
+
console.log(`Cookie expiration time set to ${COOKIE_EXPIRE_TIME} days for deployed environment`);
|
|
24
24
|
} catch (error) {
|
|
25
|
-
|
|
25
|
+
console.log("Error parsing COOKIE_EXPIRE_TIME:", error);
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
async function WriteConsoleLogs(message) {
|
|
29
|
-
const appName = process.env.AppName;
|
|
30
|
-
try {
|
|
31
|
-
const query = `
|
|
32
|
-
INSERT INTO mbkauthlogs (app_name, message)
|
|
33
|
-
VALUES ($1, $2)
|
|
34
|
-
`;
|
|
35
|
-
await dblogin.query(query, [appName, message]);
|
|
36
|
-
console.log(`Logged message: ${message}`);
|
|
37
|
-
} catch (error) {
|
|
38
|
-
console.error("Error logging message:", error.message);
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
28
|
router.use(express.json());
|
|
43
29
|
router.use(express.urlencoded({ extended: true }));
|
|
44
30
|
|
|
@@ -105,7 +91,7 @@ router.use(async (req, res, next) => {
|
|
|
105
91
|
req.session.user.role = null;
|
|
106
92
|
}
|
|
107
93
|
} catch (error) {
|
|
108
|
-
|
|
94
|
+
console.log("Error fetching user role:", error.message);
|
|
109
95
|
req.session.user.role = null; // Fallback to null role
|
|
110
96
|
}
|
|
111
97
|
}
|
|
@@ -115,7 +101,7 @@ router.use(async (req, res, next) => {
|
|
|
115
101
|
router.use(async (req, res, next) => {
|
|
116
102
|
// Check for sessionId cookie if session is not initialized
|
|
117
103
|
if (!req.session.user && req.cookies && req.cookies.sessionId) {
|
|
118
|
-
|
|
104
|
+
console.log("Restoring session from sessionId cookie"); // Log session restoration
|
|
119
105
|
const sessionId = req.cookies.sessionId;
|
|
120
106
|
const query = `SELECT * FROM "Users" WHERE "SessionId" = $1`;
|
|
121
107
|
const result = await dblogin.query(query, [sessionId]);
|
|
@@ -127,7 +113,7 @@ router.use(async (req, res, next) => {
|
|
|
127
113
|
username: user.UserName,
|
|
128
114
|
sessionId,
|
|
129
115
|
};
|
|
130
|
-
|
|
116
|
+
console.log(`Session restored for user: ${user.UserName}`); // Log successful session restoration
|
|
131
117
|
} else {
|
|
132
118
|
console.warn("No matching session found for sessionId"); // Log if no session is found
|
|
133
119
|
}
|
|
@@ -147,19 +133,19 @@ router.post("/mbkauthe/api/terminateAllSessions", authenticate(process.env.Main_
|
|
|
147
133
|
// Destroy all sessions on the server
|
|
148
134
|
req.session.destroy((err) => {
|
|
149
135
|
if (err) {
|
|
150
|
-
|
|
136
|
+
console.log("Error destroying session:", err);
|
|
151
137
|
return res
|
|
152
138
|
.status(500)
|
|
153
139
|
.json({ success: false, message: "Failed to terminate sessions" });
|
|
154
140
|
}
|
|
155
|
-
|
|
141
|
+
console.log("All sessions terminated successfully");
|
|
156
142
|
res.status(200).json({
|
|
157
143
|
success: true,
|
|
158
144
|
message: "All sessions terminated successfully",
|
|
159
145
|
});
|
|
160
146
|
});
|
|
161
147
|
} catch (err) {
|
|
162
|
-
|
|
148
|
+
console.log("Database query error during session termination:", err);
|
|
163
149
|
res
|
|
164
150
|
.status(500)
|
|
165
151
|
.json({ success: false, message: "Internal Server Error" });
|
|
@@ -168,10 +154,10 @@ router.post("/mbkauthe/api/terminateAllSessions", authenticate(process.env.Main_
|
|
|
168
154
|
);
|
|
169
155
|
|
|
170
156
|
router.post("/mbkauthe/api/login", async (req, res) => {
|
|
171
|
-
|
|
157
|
+
console.log("Login request received"); // Log when login is initiated
|
|
172
158
|
|
|
173
159
|
const { username, password, token, recaptcha } = req.body;
|
|
174
|
-
|
|
160
|
+
console.log(`Login attempt for username: ${username}`); // Log username
|
|
175
161
|
|
|
176
162
|
const secretKey = process.env.RECAPTCHA_SECRET_KEY;
|
|
177
163
|
const verificationUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${recaptcha}`;
|
|
@@ -181,42 +167,42 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
181
167
|
try {
|
|
182
168
|
const response = await fetch(verificationUrl, { method: 'POST' });
|
|
183
169
|
const body = await response.json();
|
|
184
|
-
|
|
170
|
+
console.log("reCAPTCHA verification response:", body); // Log reCAPTCHA response
|
|
185
171
|
|
|
186
172
|
if (!body.success) {
|
|
187
|
-
|
|
173
|
+
console.log("Failed reCAPTCHA verification");
|
|
188
174
|
return res.status(400).json({ success: false, message: "Failed reCAPTCHA verification" });
|
|
189
175
|
}
|
|
190
176
|
} catch (err) {
|
|
191
|
-
|
|
177
|
+
console.log("Error during reCAPTCHA verification:", err);
|
|
192
178
|
return res.status(500).json({ success: false, message: "Internal Server Error" });
|
|
193
179
|
}
|
|
194
180
|
}
|
|
195
181
|
|
|
196
182
|
if (!username || !password) {
|
|
197
|
-
|
|
183
|
+
console.log("Missing username or password");
|
|
198
184
|
return res.status(400).json({
|
|
199
185
|
success: false,
|
|
200
186
|
message: "Username and password are required",
|
|
201
187
|
});
|
|
202
188
|
}
|
|
203
189
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
190
|
+
console.log("RECAPTCHA_SECRET_KEY:", process.env.RECAPTCHA_SECRET_KEY); // Log reCAPTCHA secret key
|
|
191
|
+
console.log("SESSION_SECRET_KEY:", process.env.SESSION_SECRET_KEY); // Log reCAPTCHA secret key
|
|
192
|
+
console.log("LOGIN_DB:", process.env.LOGIN_DB); // Log reCAPTCHA secret key
|
|
193
|
+
console.log("COOKIE_EXPIRE_TIME:", process.env.COOKIE_EXPIRE_TIME); // Log reCAPTCHA secret key
|
|
194
|
+
console.log("DOMAIN:", process.env.DOMAIN); // Log reCAPTCHA secret key
|
|
195
|
+
console.log("IS_DEPLOYED:", process.env.IS_DEPLOYED); // Log reCAPTCHA secret key
|
|
196
|
+
console.log("MBKAUTH_TWO_FA_ENABLE:", process.env.MBKAUTH_TWO_FA_ENABLE); // Log reCAPTCHA secret key
|
|
211
197
|
|
|
212
198
|
try {
|
|
213
199
|
// Query to check if the username exists
|
|
214
200
|
const userQuery = `SELECT * FROM "Users" WHERE "UserName" = $1`;
|
|
215
201
|
const userResult = await dblogin.query(userQuery, [username]);
|
|
216
|
-
|
|
202
|
+
console.log("User query result:", userResult.rows); // Log user query result
|
|
217
203
|
|
|
218
204
|
if (userResult.rows.length === 0) {
|
|
219
|
-
|
|
205
|
+
console.log(`Username does not exist: ${username}`);
|
|
220
206
|
return res.status(404).json({ success: false, message: "Username does not exist" });
|
|
221
207
|
}
|
|
222
208
|
|
|
@@ -224,13 +210,13 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
224
210
|
|
|
225
211
|
// Check if the password matches
|
|
226
212
|
if (user.Password !== password) {
|
|
227
|
-
|
|
213
|
+
console.log(`Incorrect password for username: ${username}`);
|
|
228
214
|
return res.status(401).json({ success: false, message: "Incorrect password" });
|
|
229
215
|
}
|
|
230
216
|
|
|
231
217
|
// Check if the account is inactive
|
|
232
218
|
if (!user.Active) {
|
|
233
|
-
|
|
219
|
+
console.log(`Inactive account for username: ${username}`);
|
|
234
220
|
return res.status(403).json({ success: false, message: "Account is inactive" });
|
|
235
221
|
}
|
|
236
222
|
|
|
@@ -238,11 +224,11 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
238
224
|
let sharedSecret;
|
|
239
225
|
const query = `SELECT "TwoFAStatus", "TwoFASecret" FROM "TwoFA" WHERE "UserName" = $1`;
|
|
240
226
|
const twoFAResult = await dblogin.query(query, [username]);
|
|
241
|
-
|
|
227
|
+
console.log("TwoFA query result:", twoFAResult.rows); // Log TwoFA query result
|
|
242
228
|
|
|
243
229
|
sharedSecret = twoFAResult.rows[0]?.TwoFASecret;
|
|
244
230
|
if (twoFAResult.rows.length > 0 && twoFAResult.rows[0].TwoFAStatus && !token) {
|
|
245
|
-
|
|
231
|
+
console.log("2FA code required but not provided");
|
|
246
232
|
return res.status(401).json({ success: false, message: "Please Enter 2FA code" });
|
|
247
233
|
}
|
|
248
234
|
|
|
@@ -255,7 +241,7 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
255
241
|
});
|
|
256
242
|
|
|
257
243
|
if (!tokenValidates) {
|
|
258
|
-
|
|
244
|
+
console.log(`Invalid 2FA code for username: ${username}`);
|
|
259
245
|
return res.status(401).json({ success: false, message: "Invalid 2FA code" });
|
|
260
246
|
}
|
|
261
247
|
}
|
|
@@ -263,7 +249,7 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
263
249
|
|
|
264
250
|
// Generate session ID
|
|
265
251
|
const sessionId = crypto.randomBytes(256).toString("hex");
|
|
266
|
-
|
|
252
|
+
console.log(`Generated session ID for username: ${username}`); // Log session ID
|
|
267
253
|
|
|
268
254
|
await dblogin.query(`UPDATE "Users" SET "SessionId" = $1 WHERE "id" = $2`, [
|
|
269
255
|
sessionId,
|
|
@@ -276,7 +262,7 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
276
262
|
username: user.UserName,
|
|
277
263
|
sessionId,
|
|
278
264
|
};
|
|
279
|
-
|
|
265
|
+
console.log(`Session stored for user: ${user.UserName}, sessionId: ${sessionId}`); // Log session storage
|
|
280
266
|
|
|
281
267
|
// Set a cookie accessible across subDOMAINs
|
|
282
268
|
res.cookie("sessionId", sessionId, {
|
|
@@ -285,16 +271,16 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
285
271
|
httpOnly: true,
|
|
286
272
|
secure: process.env.IS_DEPLOYED === 'true', // Use secure cookies in production
|
|
287
273
|
});
|
|
288
|
-
|
|
274
|
+
console.log(`Cookie set for user: ${user.UserName}, sessionId: ${sessionId}`); // Log cookie setting
|
|
289
275
|
|
|
290
|
-
|
|
276
|
+
console.log(`User "${username}" logged in successfully`);
|
|
291
277
|
res.status(200).json({
|
|
292
278
|
success: true,
|
|
293
279
|
message: "Login successful",
|
|
294
280
|
sessionId,
|
|
295
281
|
});
|
|
296
282
|
} catch (err) {
|
|
297
|
-
|
|
283
|
+
console.log("Error during login process:", err);
|
|
298
284
|
res.status(500).json({ success: false, message: "Internal Server Error" });
|
|
299
285
|
}
|
|
300
286
|
});
|
|
@@ -307,22 +293,22 @@ router.post("/mbkauthe/api/logout", async (req, res) => {
|
|
|
307
293
|
const result = await dblogin.query(query, [id]);
|
|
308
294
|
|
|
309
295
|
if (result.rows.length > 0 && !result.rows[0].Active) {
|
|
310
|
-
|
|
296
|
+
console.log("Account is inactive during logout");
|
|
311
297
|
}
|
|
312
298
|
|
|
313
299
|
req.session.destroy((err) => {
|
|
314
300
|
if (err) {
|
|
315
|
-
|
|
301
|
+
console.log("Error destroying session:", err);
|
|
316
302
|
return res.status(500).json({ success: false, message: "Logout failed" });
|
|
317
303
|
}
|
|
318
304
|
// Clear both session cookies
|
|
319
305
|
res.clearCookie("connect.sid");
|
|
320
306
|
res.clearCookie("sessionId"); // Clear the sessionId cookie used for restoration
|
|
321
|
-
|
|
307
|
+
console.log(`User "${username}" logged out successfully`);
|
|
322
308
|
res.status(200).json({ success: true, message: "Logout successful" });
|
|
323
309
|
});
|
|
324
310
|
} catch (err) {
|
|
325
|
-
|
|
311
|
+
console.log("Database query error during logout:", err);
|
|
326
312
|
res.status(500).json({ success: false, message: "Internal Server Error" });
|
|
327
313
|
}
|
|
328
314
|
} else {
|