mbkauthe 1.1.4 → 1.1.6

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/index.js CHANGED
@@ -45,7 +45,6 @@ if (process.env.test === "true") {
45
45
  });
46
46
  }
47
47
 
48
- export { validateSession, checkRolePermission, validateSessionAndRole, getUserData, authenticate } from "./lib/validateSessionAndRole.js";
48
+ export { validateSession, checkRolePermission, validateSessionAndRole, getUserData, authenticate, authapi } from "./lib/validateSessionAndRole.js";
49
49
  export { dblogin } from "./lib/pool.js";
50
- export { authapi } from "./lib/authapi.js";
51
50
  export default router;
package/lib/main.js CHANGED
@@ -246,6 +246,11 @@ router.post("/mbkauthe/api/login", LoginLimit, async (req, res) => {
246
246
  const sessionId = crypto.randomBytes(256).toString("hex");
247
247
  console.log(`Generated session ID for username: ${username}`);
248
248
 
249
+ // Delete old session record for this user
250
+ if (user.SessionId) {
251
+ await dblogin.query('DELETE FROM "session" WHERE username = $1', [user.UserName]);
252
+ }
253
+
249
254
  await dblogin.query(`UPDATE "Users" SET "SessionId" = $1 WHERE "id" = $2`, [
250
255
  sessionId,
251
256
  user.id,
@@ -262,11 +267,32 @@ router.post("/mbkauthe/api/login", LoginLimit, async (req, res) => {
262
267
  res.cookie("sessionId", sessionId, cookieOptions);
263
268
  console.log(req.session.user);
264
269
 
265
- console.log(`User "${username}" logged in successfully`);
266
- res.status(200).json({
267
- success: true,
268
- message: "Login successful",
269
- sessionId,
270
+
271
+ // Save session and update username in session table
272
+ req.session.save(async (err) => {
273
+ if (err) {
274
+ console.log("Session save error:", err);
275
+ return res.status(500).json({ success: false, message: "Internal Server Error" });
276
+ }
277
+ try {
278
+ await dblogin.query(
279
+ 'UPDATE "session" SET username = $1 WHERE sid = $2',
280
+ [user.UserName, req.sessionID]
281
+ );
282
+ } catch (e) {
283
+ console.log("Failed to update username in session table:", e);
284
+ }
285
+
286
+ const cookieOptions = getCookieOptions();
287
+ res.cookie("sessionId", sessionId, cookieOptions);
288
+ console.log(req.session.user);
289
+
290
+ console.log(`User "${username}" logged in successfully`);
291
+ res.status(200).json({
292
+ success: true,
293
+ message: "Login successful",
294
+ sessionId,
295
+ });
270
296
  });
271
297
  } catch (err) {
272
298
  console.log("Error during login process:", err);
@@ -1,5 +1,6 @@
1
1
  import { dblogin } from "./pool.js";
2
2
  const mbkautheVar = JSON.parse(process.env.mbkautheVar);
3
+ let pool = dblogin;
3
4
 
4
5
  const getCookieOptions = () => ({
5
6
  maxAge: mbkautheVar.COOKIE_EXPIRE_TIME * 24 * 60 * 60 * 1000,
@@ -210,4 +211,101 @@ const authenticate = (authentication) => {
210
211
  };
211
212
  };
212
213
 
213
- export { validateSession, checkRolePermission, validateSessionAndRole, getUserData, authenticate };
214
+ const authapi = (requiredRole = []) => {
215
+ return (req, res, next) => {
216
+ const token = req.headers["authorization"];
217
+
218
+ if (typeof token === 'string') {
219
+ console.log("[authapi] Received request with token:", token[0] + token[1] + token[2], ".....", token[63]);
220
+ } else {
221
+ console.log("[authapi] Token is not a valid string:", token);
222
+ }
223
+
224
+ if (!token) {
225
+ console.log("[authapi] No token provided in the request headers");
226
+ return res.status(401).json({
227
+ success: false,
228
+ message: "Authorization token is required"
229
+ });
230
+ }
231
+
232
+ console.log("[authapi] Querying database to validate token");
233
+ const tokenQuery = 'SELECT * FROM "UserAuthApiKey" WHERE "key" = $1';
234
+ pool.query(tokenQuery, [token], (err, result) => {
235
+ if (err) {
236
+ console.error("[authapi] Database query error while validating token:", err);
237
+ return res.status(500).json({
238
+ success: false,
239
+ message: "Internal Server Error"
240
+ });
241
+ }
242
+
243
+ if (result.rows.length === 0) {
244
+ console.log("[authapi] Invalid token provided:", token);
245
+ return res.status(401).json({
246
+ success: false,
247
+ message: "The AuthApiToken Is Invalid"
248
+ });
249
+ }
250
+
251
+ const username = result.rows[0].username;
252
+ console.log("[authapi] Token is valid. Associated username:", username);
253
+
254
+ console.log("[authapi] Querying database to validate user and role");
255
+ const userQuery = `
256
+ SELECT id, "UserName", "Active", "Role" FROM "Users"
257
+ WHERE "UserName" = $1 AND "Active" = true
258
+ `;
259
+
260
+ pool.query(userQuery, [username], (err, userResult) => {
261
+ if (err) {
262
+ console.error("[authapi] Database query error while validating user:", err);
263
+ return res.status(500).json({
264
+ success: false,
265
+ message: "Internal Server Error"
266
+ });
267
+ }
268
+
269
+ if (userResult.rows.length === 0) {
270
+ console.log("[authapi] User does not exist or is not active. Username:", username);
271
+ return res.status(401).json({
272
+ success: false,
273
+ message: "User does not exist or is not active",
274
+ });
275
+ }
276
+
277
+ if (username === "demo") {
278
+ console.log("[authapi] Demo user attempted to access an endpoint. Access denied.");
279
+ return res.status(401).json({
280
+ success: false,
281
+ message: "Demo user is not allowed to access endpoints",
282
+ });
283
+ }
284
+
285
+ const user = userResult.rows[0];
286
+ console.log("[authapi] User is valid. User details:", user);
287
+
288
+ // Check if role is required and if user has it
289
+ if ((requiredRole && user.Role !== requiredRole) && user.Role !== "SuperAdmin") {
290
+ console.log(`[authapi] User does not have the required role. Required: ${requiredRole}, User's role: ${user.Role}`);
291
+ return res.status(403).json({
292
+ success: false,
293
+ message: `Access denied. Required role: ${requiredRole}`,
294
+ });
295
+ }
296
+
297
+ console.log("[authapi] User has the required role or no specific role is required. Proceeding to next middleware.");
298
+ req.user = {
299
+ username: user.UserName,
300
+ role: user.Role,
301
+ // Add other user properties you might need
302
+ };
303
+
304
+ console.log("[authapi] Token and user validation successful. Passing control to next middleware.");
305
+ next();
306
+ });
307
+ });
308
+ };
309
+ };
310
+
311
+ export { validateSession, checkRolePermission, validateSessionAndRole, getUserData, authenticate, authapi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mbkauthe",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "MBKTechStudio's reusable authentication system for Node.js applications.",
5
5
  "main": "index.js",
6
6
  "type": "module",
package/lib/authapi.js DELETED
@@ -1,57 +0,0 @@
1
- import { pool } from "./pool.js";
2
-
3
- export const authapi = () => {
4
- return (req, res, next) => {
5
- const token = req.headers["authorization"];
6
-
7
- // Query to check if the token exists in UserAuthApiKey table
8
- const tokenQuery = 'SELECT * FROM "UserAuthApiKey" WHERE "key" = $1';
9
- pool.query(tokenQuery, [token], (err, result) => {
10
- if (err) {
11
- console.error("Database query error:", err);
12
- return res
13
- .status(500)
14
- .json({ success: false, message: "Internal Server Error" });
15
- }
16
-
17
- if (result.rows.length === 0) {
18
- console.log("Invalid token");
19
- return res
20
- .status(401)
21
- .json({ success: false, message: "The AuthApiToken Is InValid" });
22
- }
23
-
24
- const username = result.rows[0].username;
25
-
26
- // Query to check if the user exists and is active in Users table
27
- const userQuery =
28
- 'SELECT * FROM "Users" WHERE "UserName" = $1 AND "Active" = true';
29
- pool.query(userQuery, [username], (err, userResult) => {
30
- if (username === "demo") {
31
- console.log("Demo user is not allowed to access this endpoint");
32
- return res.status(401).json({
33
- success: false,
34
- message: "Demo user is not allowed to access endpoints",
35
- });
36
- }
37
- if (err) {
38
- console.error("Database query error:", err);
39
- return res
40
- .status(500)
41
- .json({ success: false, message: "Internal Server Error" });
42
- }
43
-
44
- if (userResult.rows.length === 0) {
45
- console.log("User does not exist or is not active");
46
- return res.status(401).json({
47
- success: false,
48
- message: "User does not exist or is not active",
49
- });
50
- }
51
-
52
- console.log("Token and user are valid");
53
- next();
54
- });
55
- });
56
- };
57
- };