mbkauthe 1.0.5 → 1.0.7
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/.env.example +11 -0
- package/.github/workflows/publish.yml +7 -0
- package/README.md +9 -7
- package/index.js +19 -17
- package/lib/main.js +86 -104
- package/lib/pool.js +19 -2
- package/lib/validateSessionAndRole.js +45 -15
- package/package.json +1 -2
- package/lib/auth.js +0 -13
package/.env.example
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
mbkautheVar='{
|
|
2
|
+
"RECAPTCHA_SECRET_KEY": "your-recaptcha-secret-key",
|
|
3
|
+
"SESSION_SECRET_KEY": "your-session-secret-key",
|
|
4
|
+
"IS_DEPLOYED": "true",
|
|
5
|
+
"LOGIN_DB": "postgres://username:password@host:port/database",
|
|
6
|
+
"MBKAUTH_TWO_FA_ENABLE": "false",
|
|
7
|
+
"COOKIE_EXPIRE_TIME": 2,
|
|
8
|
+
"DOMAIN": "yourdomain.com"
|
|
9
|
+
}'
|
|
10
|
+
|
|
11
|
+
# See env.md for more details
|
package/README.md
CHANGED
|
@@ -55,13 +55,15 @@ app.listen(3000, () => {
|
|
|
55
55
|
|
|
56
56
|
Example `.env` file:
|
|
57
57
|
```code
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
MBKAUTH_TWO_FA_ENABLE
|
|
64
|
-
COOKIE_EXPIRE_TIME
|
|
58
|
+
mbkautheVar='{
|
|
59
|
+
"RECAPTCHA_SECRET_KEY": "your-recaptcha-secret-key",
|
|
60
|
+
"SESSION_SECRET_KEY": "your-session-secret-key",
|
|
61
|
+
"IS_DEPLOYED": "true",
|
|
62
|
+
"LOGIN_DB": "postgres://username:password@host:port/database",
|
|
63
|
+
"MBKAUTH_TWO_FA_ENABLE": "false",
|
|
64
|
+
"COOKIE_EXPIRE_TIME": 2,
|
|
65
|
+
"DOMAIN": "yourdomain.com"
|
|
66
|
+
}'
|
|
65
67
|
```
|
|
66
68
|
|
|
67
69
|
## API Endpoints
|
package/index.js
CHANGED
|
@@ -1,23 +1,25 @@
|
|
|
1
|
-
import dotenv from "dotenv";
|
|
2
|
-
import Joi from "joi";
|
|
3
1
|
import router from "./lib/main.js";
|
|
2
|
+
|
|
3
|
+
import dotenv from "dotenv";
|
|
4
4
|
dotenv.config();
|
|
5
|
+
const mbkautheVar = JSON.parse(process.env.mbkautheVar);
|
|
6
|
+
if (!mbkautheVar) {
|
|
7
|
+
throw new Error("mbkautheVar is not defined");
|
|
8
|
+
}
|
|
9
|
+
const requiredKeys = ["RECAPTCHA_SECRET_KEY", "SESSION_SECRET_KEY", "IS_DEPLOYED", "LOGIN_DB", "MBKAUTH_TWO_FA_ENABLE", "DOMAIN"];
|
|
10
|
+
requiredKeys.forEach(key => {
|
|
11
|
+
if (!mbkautheVar[key]) {
|
|
12
|
+
throw new Error(`mbkautheVar.${key} is required`);
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
if (mbkautheVar.COOKIE_EXPIRE_TIME !== undefined) {
|
|
16
|
+
const expireTime = parseFloat(mbkautheVar.COOKIE_EXPIRE_TIME);
|
|
17
|
+
if (isNaN(expireTime) || expireTime <= 0) {
|
|
18
|
+
throw new Error("mbkautheVar.COOKIE_EXPIRE_TIME must be a valid positive number");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
5
21
|
|
|
6
|
-
const envSchema = Joi.object({
|
|
7
|
-
RECAPTCHA_SECRET_KEY: Joi.string().required(),
|
|
8
|
-
SESSION_SECRET_KEY: Joi.string().required(),
|
|
9
|
-
IS_DEPLOYED: Joi.string().valid("true", "false").required(),
|
|
10
|
-
LOGIN_DB: Joi.string().uri().required(),
|
|
11
|
-
MBKAUTH_TWO_FA_ENABLE: Joi.string().valid("true", "false").required(),
|
|
12
|
-
COOKIE_EXPIRE_TIME: Joi.number().integer().positive(),
|
|
13
|
-
DOMAIN: Joi.string().required(),
|
|
14
|
-
}).unknown(true);
|
|
15
22
|
|
|
16
|
-
|
|
17
|
-
if (error) {
|
|
18
|
-
throw new Error(`Environment variable validation error: ${error.message}`);
|
|
19
|
-
}
|
|
20
|
-
export { validateSession, checkRolePermission, validateSessionAndRole, getUserData } from "./lib/validateSessionAndRole.js";
|
|
21
|
-
export { authenticate } from "./lib/auth.js";
|
|
23
|
+
export { validateSession, checkRolePermission, validateSessionAndRole, getUserData, authenticate } from "./lib/validateSessionAndRole.js";
|
|
22
24
|
export { dblogin } from "./lib/pool.js";
|
|
23
25
|
export default router;
|
package/lib/main.js
CHANGED
|
@@ -3,119 +3,103 @@ import crypto from "crypto";
|
|
|
3
3
|
import session from "express-session";
|
|
4
4
|
import pgSession from "connect-pg-simple";
|
|
5
5
|
const PgSession = pgSession(session);
|
|
6
|
-
import dotenv from "dotenv";
|
|
7
6
|
import { dblogin } from "./pool.js";
|
|
8
|
-
import { authenticate } from "./
|
|
7
|
+
import { authenticate } from "./validateSessionAndRole.js";
|
|
9
8
|
import fetch from 'node-fetch';
|
|
10
|
-
import cookieParser from "cookie-parser";
|
|
9
|
+
import cookieParser from "cookie-parser";
|
|
10
|
+
|
|
11
|
+
|
|
11
12
|
|
|
13
|
+
import dotenv from "dotenv";
|
|
12
14
|
dotenv.config();
|
|
15
|
+
const mbkautheVar = JSON.parse(process.env.mbkautheVar);
|
|
16
|
+
if (!mbkautheVar) {
|
|
17
|
+
throw new Error("mbkautheVar is not defined");
|
|
18
|
+
}
|
|
19
|
+
const requiredKeys = ["RECAPTCHA_SECRET_KEY", "SESSION_SECRET_KEY", "IS_DEPLOYED", "LOGIN_DB", "MBKAUTH_TWO_FA_ENABLE", "DOMAIN"];
|
|
20
|
+
requiredKeys.forEach(key => {
|
|
21
|
+
if (!mbkautheVar[key]) {
|
|
22
|
+
throw new Error(`mbkautheVar.${key} is required`);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
if (mbkautheVar.COOKIE_EXPIRE_TIME !== undefined) {
|
|
26
|
+
const expireTime = parseFloat(mbkautheVar.COOKIE_EXPIRE_TIME);
|
|
27
|
+
if (isNaN(expireTime) || expireTime <= 0) {
|
|
28
|
+
throw new Error("mbkautheVar.COOKIE_EXPIRE_TIME must be a valid positive number");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
13
33
|
const router = express.Router();
|
|
14
|
-
let COOKIE_EXPIRE_TIME = 2 * 24 * 60 * 60 * 1000; //2 days
|
|
34
|
+
let COOKIE_EXPIRE_TIME = 2 * 24 * 60 * 60 * 1000; // 2 days
|
|
15
35
|
|
|
16
36
|
try {
|
|
17
|
-
const parsedExpireTime = parseInt(
|
|
37
|
+
const parsedExpireTime = parseInt(mbkautheVar.COOKIE_EXPIRE_TIME, 10);
|
|
18
38
|
if (!isNaN(parsedExpireTime) && parsedExpireTime > 0) {
|
|
19
|
-
COOKIE_EXPIRE_TIME = parsedExpireTime * 24 * 60 * 60 * 1000;
|
|
39
|
+
COOKIE_EXPIRE_TIME = parsedExpireTime * 24 * 60 * 60 * 1000;
|
|
20
40
|
} else {
|
|
21
|
-
console.warn("Invalid COOKIE_EXPIRE_TIME
|
|
41
|
+
console.warn("Invalid COOKIE_EXPIRE_TIME, using default value");
|
|
22
42
|
}
|
|
23
|
-
console.log(`Cookie expiration time set to ${COOKIE_EXPIRE_TIME} days for deployed environment`);
|
|
24
43
|
} catch (error) {
|
|
25
44
|
console.log("Error parsing COOKIE_EXPIRE_TIME:", error);
|
|
26
45
|
}
|
|
27
46
|
|
|
28
|
-
|
|
29
|
-
router.use(express.urlencoded({ extended: true }));
|
|
30
|
-
|
|
31
|
-
router.use(
|
|
32
|
-
session({
|
|
33
|
-
store: new PgSession({
|
|
34
|
-
pool: dblogin, // Connection pool
|
|
35
|
-
tableName: "session", // Use another table-name than the default "session" one
|
|
36
|
-
}),
|
|
37
|
-
secret: process.env.SESSION_SECRET_KEY, // Replace with your secret key
|
|
38
|
-
resave: false,
|
|
39
|
-
saveUninitialized: false,
|
|
40
|
-
cookie: {
|
|
41
|
-
maxAge: COOKIE_EXPIRE_TIME,
|
|
42
|
-
DOMAIN: process.env.IS_DEPLOYED === 'true' ? `.${process.env.DOMAIN}` : undefined, // Use root DOMAIN for subDOMAIN sharing
|
|
43
|
-
httpOnly: true,
|
|
44
|
-
secure: process.env.IS_DEPLOYED === 'true', // Use secure cookies in production
|
|
45
|
-
},
|
|
46
|
-
})
|
|
47
|
-
);
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
router.use(cookieParser()); // Use cookie-parser middleware
|
|
52
|
-
|
|
47
|
+
// Enable CORS for subdomains
|
|
53
48
|
router.use((req, res, next) => {
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
req.session.otherInfo = {
|
|
61
|
-
ip: formattedIp,
|
|
62
|
-
browser: userAgent,
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
next();
|
|
66
|
-
} else {
|
|
67
|
-
next();
|
|
49
|
+
const origin = req.headers.origin;
|
|
50
|
+
if (origin && origin.endsWith(`.${mbkautheVar.DOMAIN}`)) {
|
|
51
|
+
res.header('Access-Control-Allow-Origin', origin);
|
|
52
|
+
res.header('Access-Control-Allow-Credentials', 'true');
|
|
53
|
+
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
|
|
54
|
+
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
68
55
|
}
|
|
56
|
+
next();
|
|
69
57
|
});
|
|
70
58
|
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
59
|
+
router.use(express.json());
|
|
60
|
+
router.use(express.urlencoded({ extended: true }));
|
|
61
|
+
router.use(cookieParser());
|
|
62
|
+
|
|
63
|
+
// Configure session with proper domain settings
|
|
64
|
+
const sessionConfig = {
|
|
65
|
+
store: new PgSession({
|
|
66
|
+
pool: dblogin,
|
|
67
|
+
tableName: "session",
|
|
68
|
+
}),
|
|
69
|
+
secret: mbkautheVar.SESSION_SECRET_KEY,
|
|
70
|
+
resave: false,
|
|
71
|
+
saveUninitialized: false,
|
|
72
|
+
cookie: {
|
|
73
|
+
maxAge: COOKIE_EXPIRE_TIME,
|
|
74
|
+
domain: mbkautheVar.IS_DEPLOYED === 'true' ? `.${mbkautheVar.DOMAIN}` : undefined,
|
|
75
|
+
httpOnly: true,
|
|
76
|
+
secure: mbkautheVar.IS_DEPLOYED === 'true',
|
|
77
|
+
sameSite: 'lax',
|
|
78
|
+
},
|
|
79
|
+
name: 'mbkauthe.sid' // Unique session cookie name
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
router.use(session(sessionConfig));
|
|
83
|
+
|
|
84
|
+
// Middleware to handle session restoration from sessionId cookie
|
|
74
85
|
router.use(async (req, res, next) => {
|
|
75
|
-
if (req.session && req.
|
|
86
|
+
if (!req.session.user && req.cookies.sessionId) {
|
|
76
87
|
try {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
const query = `SELECT "Role" FROM "Users" WHERE "UserName" = $1`;
|
|
83
|
-
const result = await dblogin.query(query, [req.session.user.username]);
|
|
88
|
+
const sessionId = req.cookies.sessionId;
|
|
89
|
+
const query = `SELECT * FROM "Users" WHERE "SessionId" = $1`;
|
|
90
|
+
const result = await dblogin.query(query, [sessionId]);
|
|
84
91
|
|
|
85
92
|
if (result.rows.length > 0) {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
93
|
+
const user = result.rows[0];
|
|
94
|
+
req.session.user = {
|
|
95
|
+
id: user.id,
|
|
96
|
+
username: user.UserName,
|
|
97
|
+
sessionId,
|
|
98
|
+
};
|
|
99
|
+
console.log(`Session restored for user: ${user.UserName}`);
|
|
92
100
|
}
|
|
93
|
-
} catch (
|
|
94
|
-
console.
|
|
95
|
-
req.session.user.role = null; // Fallback to null role
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
next();
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
router.use(async (req, res, next) => {
|
|
102
|
-
// Check for sessionId cookie if session is not initialized
|
|
103
|
-
if (!req.session.user && req.cookies && req.cookies.sessionId) {
|
|
104
|
-
console.log("Restoring session from sessionId cookie"); // Log session restoration
|
|
105
|
-
const sessionId = req.cookies.sessionId;
|
|
106
|
-
const query = `SELECT * FROM "Users" WHERE "SessionId" = $1`;
|
|
107
|
-
const result = await dblogin.query(query, [sessionId]);
|
|
108
|
-
|
|
109
|
-
if (result.rows.length > 0) {
|
|
110
|
-
const user = result.rows[0];
|
|
111
|
-
req.session.user = {
|
|
112
|
-
id: user.id,
|
|
113
|
-
username: user.UserName,
|
|
114
|
-
sessionId,
|
|
115
|
-
};
|
|
116
|
-
console.log(`Session restored for user: ${user.UserName}`); // Log successful session restoration
|
|
117
|
-
} else {
|
|
118
|
-
console.warn("No matching session found for sessionId"); // Log if no session is found
|
|
101
|
+
} catch (err) {
|
|
102
|
+
console.error("Session restoration error:", err);
|
|
119
103
|
}
|
|
120
104
|
}
|
|
121
105
|
next();
|
|
@@ -123,7 +107,7 @@ router.use(async (req, res, next) => {
|
|
|
123
107
|
|
|
124
108
|
//Invoke-RestMethod -Uri http://localhost:3030/terminateAllSessions -Method POST
|
|
125
109
|
// Terminate all sessions route
|
|
126
|
-
router.post("/mbkauthe/api/terminateAllSessions", authenticate(
|
|
110
|
+
router.post("/mbkauthe/api/terminateAllSessions", authenticate(mbkautheVar.Main_SECRET_TOKEN), async (req, res) => {
|
|
127
111
|
try {
|
|
128
112
|
await dblogin.query(`UPDATE "Users" SET "SessionId" = NULL`);
|
|
129
113
|
|
|
@@ -159,11 +143,17 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
159
143
|
const { username, password, token, recaptcha } = req.body;
|
|
160
144
|
console.log(`Login attempt for username: ${username}`); // Log username
|
|
161
145
|
|
|
162
|
-
const secretKey =
|
|
146
|
+
const secretKey = mbkautheVar.RECAPTCHA_SECRET_KEY;
|
|
163
147
|
const verificationUrl = `https://www.google.com/recaptcha/api/siteverify?secret=${secretKey}&response=${recaptcha}`;
|
|
164
148
|
|
|
149
|
+
let BypassUsers = ["ibnekhalid", "maaz.waheed", "support"];
|
|
150
|
+
|
|
165
151
|
// Bypass recaptcha for specific users
|
|
166
|
-
if (
|
|
152
|
+
if (!BypassUsers.includes(username)) {
|
|
153
|
+
if (!recaptcha) {
|
|
154
|
+
console.log("Missing reCAPTCHA token");
|
|
155
|
+
return res.status(400).json({ success: false, message: "Please complete the reCAPTCHA" });
|
|
156
|
+
}
|
|
167
157
|
try {
|
|
168
158
|
const response = await fetch(verificationUrl, { method: 'POST' });
|
|
169
159
|
const body = await response.json();
|
|
@@ -187,14 +177,6 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
187
177
|
});
|
|
188
178
|
}
|
|
189
179
|
|
|
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
|
|
197
|
-
|
|
198
180
|
try {
|
|
199
181
|
// Query to check if the username exists
|
|
200
182
|
const userQuery = `SELECT * FROM "Users" WHERE "UserName" = $1`;
|
|
@@ -220,7 +202,7 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
220
202
|
return res.status(403).json({ success: false, message: "Account is inactive" });
|
|
221
203
|
}
|
|
222
204
|
|
|
223
|
-
if ((
|
|
205
|
+
if ((mbkautheVar.MBKAUTH_TWO_FA_ENABLE || "").toLocaleLowerCase() === "true") {
|
|
224
206
|
let sharedSecret;
|
|
225
207
|
const query = `SELECT "TwoFAStatus", "TwoFASecret" FROM "TwoFA" WHERE "UserName" = $1`;
|
|
226
208
|
const twoFAResult = await dblogin.query(query, [username]);
|
|
@@ -267,9 +249,9 @@ router.post("/mbkauthe/api/login", async (req, res) => {
|
|
|
267
249
|
// Set a cookie accessible across subDOMAINs
|
|
268
250
|
res.cookie("sessionId", sessionId, {
|
|
269
251
|
maxAge: COOKIE_EXPIRE_TIME,
|
|
270
|
-
DOMAIN:
|
|
252
|
+
DOMAIN: mbkautheVar.IS_DEPLOYED === 'true' ? `.${mbkautheVar.DOMAIN}` : undefined, // Use DOMAIN only in production
|
|
271
253
|
httpOnly: true,
|
|
272
|
-
secure:
|
|
254
|
+
secure: mbkautheVar.IS_DEPLOYED === 'true', // Use secure cookies in production
|
|
273
255
|
});
|
|
274
256
|
console.log(`Cookie set for user: ${user.UserName}, sessionId: ${sessionId}`); // Log cookie setting
|
|
275
257
|
|
package/lib/pool.js
CHANGED
|
@@ -1,12 +1,29 @@
|
|
|
1
1
|
import pkg from "pg";
|
|
2
2
|
const { Pool } = pkg;
|
|
3
|
-
import dotenv from "dotenv";
|
|
4
3
|
|
|
4
|
+
|
|
5
|
+
import dotenv from "dotenv";
|
|
5
6
|
dotenv.config();
|
|
7
|
+
const mbkautheVar = JSON.parse(process.env.mbkautheVar);
|
|
8
|
+
if (!mbkautheVar) {
|
|
9
|
+
throw new Error("mbkautheVar is not defined");
|
|
10
|
+
}
|
|
11
|
+
const requiredKeys = ["RECAPTCHA_SECRET_KEY", "SESSION_SECRET_KEY", "IS_DEPLOYED", "LOGIN_DB", "MBKAUTH_TWO_FA_ENABLE", "DOMAIN"];
|
|
12
|
+
requiredKeys.forEach(key => {
|
|
13
|
+
if (!mbkautheVar[key]) {
|
|
14
|
+
throw new Error(`mbkautheVar.${key} is required`);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
if (mbkautheVar.COOKIE_EXPIRE_TIME !== undefined) {
|
|
18
|
+
const expireTime = parseFloat(mbkautheVar.COOKIE_EXPIRE_TIME);
|
|
19
|
+
if (isNaN(expireTime) || expireTime <= 0) {
|
|
20
|
+
throw new Error("mbkautheVar.COOKIE_EXPIRE_TIME must be a valid positive number");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
6
23
|
|
|
7
24
|
// PostgreSQL connection pool for pool
|
|
8
25
|
const poolConfig = {
|
|
9
|
-
connectionString:
|
|
26
|
+
connectionString: mbkautheVar.LOGIN_DB,
|
|
10
27
|
ssl: {
|
|
11
28
|
rejectUnauthorized: true,
|
|
12
29
|
},
|
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
import { dblogin } from "./pool.js";
|
|
2
2
|
|
|
3
3
|
async function validateSession(req, res, next) {
|
|
4
|
+
// First check if we have a session cookie
|
|
5
|
+
if (!req.session.user && req.cookies.sessionId) {
|
|
6
|
+
try {
|
|
7
|
+
const sessionId = req.cookies.sessionId;
|
|
8
|
+
const query = `SELECT * FROM "Users" WHERE "SessionId" = $1`;
|
|
9
|
+
const result = await dblogin.query(query, [sessionId]);
|
|
10
|
+
|
|
11
|
+
if (result.rows.length > 0) {
|
|
12
|
+
const user = result.rows[0];
|
|
13
|
+
req.session.user = {
|
|
14
|
+
id: user.id,
|
|
15
|
+
username: user.UserName,
|
|
16
|
+
sessionId,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
} catch (err) {
|
|
20
|
+
console.error("Session validation error:", err);
|
|
21
|
+
return res.status(500).json({ success: false, message: "Internal Server Error" });
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
4
25
|
if (!req.session.user) {
|
|
5
26
|
return res.render("templates/Error/NotLoggedIn.handlebars", {
|
|
6
27
|
currentUrl: req.originalUrl,
|
|
@@ -12,37 +33,32 @@ async function validateSession(req, res, next) {
|
|
|
12
33
|
const query = `SELECT "SessionId", "Active" FROM "Users" WHERE "id" = $1`;
|
|
13
34
|
const result = await dblogin.query(query, [id]);
|
|
14
35
|
|
|
15
|
-
// Check if user exists and session ID matches
|
|
16
36
|
if (result.rows.length === 0 || result.rows[0].SessionId !== sessionId) {
|
|
17
|
-
console.log(
|
|
18
|
-
`Session invalidated for user \"${req.session.user.username}\"`
|
|
19
|
-
);
|
|
37
|
+
console.log(`Session invalidated for user "${req.session.user.username}"`);
|
|
20
38
|
req.session.destroy();
|
|
21
|
-
|
|
39
|
+
res.clearCookie("mbkauthe.sid", { domain: `.${mbkautheVar.DOMAIN}` });
|
|
40
|
+
res.clearCookie("sessionId", { domain: `.${mbkautheVar.DOMAIN}` });
|
|
22
41
|
return res.render("templates/Error/SessionExpire.handlebars", {
|
|
23
42
|
currentUrl: req.originalUrl,
|
|
24
43
|
});
|
|
25
|
-
// ...existing code...
|
|
26
44
|
}
|
|
27
45
|
|
|
28
|
-
// Check if the user account is inactive
|
|
29
46
|
if (!result.rows[0].Active) {
|
|
30
|
-
console.log(
|
|
31
|
-
`Account is inactive for user \"${req.session.user.username}\"`
|
|
32
|
-
);
|
|
47
|
+
console.log(`Account is inactive for user "${req.session.user.username}"`);
|
|
33
48
|
req.session.destroy();
|
|
34
|
-
res.clearCookie("
|
|
49
|
+
res.clearCookie("mbkauthe.sid", { domain: `.${mbkautheVar.DOMAIN}` });
|
|
50
|
+
res.clearCookie("sessionId", { domain: `.${mbkautheVar.DOMAIN}` });
|
|
35
51
|
return res.render("templates/Error/AccountInactive.handlebars", {
|
|
36
52
|
currentUrl: req.originalUrl,
|
|
37
53
|
});
|
|
38
54
|
}
|
|
39
55
|
|
|
40
|
-
next();
|
|
56
|
+
next();
|
|
41
57
|
} catch (err) {
|
|
42
58
|
console.error("Session validation error:", err);
|
|
43
59
|
res.status(500).json({ success: false, message: "Internal Server Error" });
|
|
44
60
|
}
|
|
45
|
-
}
|
|
61
|
+
}
|
|
46
62
|
|
|
47
63
|
const checkRolePermission = (requiredRole) => {
|
|
48
64
|
return async (req, res, next) => {
|
|
@@ -86,7 +102,7 @@ const checkRolePermission = (requiredRole) => {
|
|
|
86
102
|
.json({ success: false, message: "Internal Server Error" });
|
|
87
103
|
}
|
|
88
104
|
};
|
|
89
|
-
};
|
|
105
|
+
};
|
|
90
106
|
|
|
91
107
|
const validateSessionAndRole = (requiredRole) => {
|
|
92
108
|
return async (req, res, next) => {
|
|
@@ -149,4 +165,18 @@ async function getUserData(UserName, parameters) {
|
|
|
149
165
|
}
|
|
150
166
|
}
|
|
151
167
|
|
|
152
|
-
|
|
168
|
+
const authenticate = (authentication) => {
|
|
169
|
+
return (req, res, next) => {
|
|
170
|
+
const token = req.headers["authorization"];
|
|
171
|
+
console.log(`Received token: ${token}`);
|
|
172
|
+
if (token === authentication) {
|
|
173
|
+
console.log("Authentication successful");
|
|
174
|
+
next();
|
|
175
|
+
} else {
|
|
176
|
+
console.log("Authentication failed");
|
|
177
|
+
res.status(401).send("Unauthorized");
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
export { validateSession, checkRolePermission, validateSessionAndRole, getUserData, authenticate };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mbkauthe",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"description": "MBKTechStudio's reusable authentication system for Node.js applications.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -31,7 +31,6 @@
|
|
|
31
31
|
"dotenv": "^16.4.7",
|
|
32
32
|
"express": "^5.1.0",
|
|
33
33
|
"express-session": "^1.18.1",
|
|
34
|
-
"joi": "^17.13.3",
|
|
35
34
|
"node-fetch": "^3.3.2",
|
|
36
35
|
"pg": "^8.14.1"
|
|
37
36
|
}
|
package/lib/auth.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
export const authenticate = (authentication) => {
|
|
2
|
-
return (req, res, next) => {
|
|
3
|
-
const token = req.headers["authorization"];
|
|
4
|
-
console.log(`Received token: ${token}`);
|
|
5
|
-
if (token === authentication) {
|
|
6
|
-
console.log("Authentication successful");
|
|
7
|
-
next();
|
|
8
|
-
} else {
|
|
9
|
-
console.log("Authentication failed");
|
|
10
|
-
res.status(401).send("Unauthorized");
|
|
11
|
-
}
|
|
12
|
-
};
|
|
13
|
-
};
|