mbkauthe 1.0.13 → 1.0.15

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 CHANGED
@@ -4,19 +4,26 @@
4
4
 
5
5
  ## Table of Contents
6
6
 
7
- - [Introduction](#mbkauth)
8
- - [Features](#features)
9
- - [Installation](#installation)
10
- - [Usage](#usage)
11
- - [Implementation in a Project](#implementation-in-a-project)
12
- - [Basic Setup](#basic-setup)
13
- - [API Endpoints](#api-endpoints)
14
- - [Login](#login)
15
- - [Logout](#logout)
16
- - [Terminate All Sessions](#terminate-all-sessions)
17
- - [Database Structure](#database-structure)
18
- - [License](#license)
19
- - [Contact & Support](#contact--support)
7
+ - [mbkauthe](#mbkauthe)
8
+ - [Table of Contents](#table-of-contents)
9
+ - [Features](#features)
10
+ - [Installation](#installation)
11
+ - [Usage](#usage)
12
+ - [Implementation in a Project](#implementation-in-a-project)
13
+ - [Basic Setup](#basic-setup)
14
+ - [Middleware Function Documentation](#middleware-function-documentation)
15
+ - [validateSession(session)](#validatesessionsession)
16
+ - [checkRolePermission(userRole, requiredRoles)](#checkrolepermissionuserrole-requiredroles)
17
+ - [validateSessionAndRole(session, userRole, requiredRoles)](#validatesessionandrolesession-userrole-requiredroles)
18
+ - [getUserData(session)](#getuserdatasession)
19
+ - [authenticate(session)](#authenticatesession)
20
+ - [API Endpoints](#api-endpoints)
21
+ - [Login](#login)
22
+ - [Logout](#logout)
23
+ - [Terminate All Sessions](#terminate-all-sessions)
24
+ - [Database Structure](#database-structure)
25
+ - [License](#license)
26
+ - [Contact \& Support](#contact--support)
20
27
 
21
28
  `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.
22
29
 
@@ -82,6 +89,96 @@ mbkautheVar='{
82
89
  }'
83
90
  ```
84
91
 
92
+ ## Middleware Function Documentation
93
+
94
+ ### `validateSession(session)`
95
+ Validates the user's session to ensure it is active and not expired.
96
+
97
+ - **Parameters:**
98
+ - `session` (Object): The session object to validate.
99
+
100
+ - **Returns:**
101
+ - `boolean`: Returns `true` if the session is valid, otherwise `false`.
102
+
103
+ Usage
104
+ ```
105
+ // Require vaild session or to be login to access this page
106
+ router.get(["/home"], validateSession, (req, res) => {
107
+ // Restricted Code
108
+ });
109
+ ```
110
+
111
+ ---
112
+
113
+ ### `checkRolePermission(userRole, requiredRoles)`
114
+ Checks if the user has the required role permissions.
115
+
116
+ - **Parameters:**
117
+ - `userRole` (string): The role of the user.
118
+ - `requiredRoles`(optional) (string[]): An array of roles that are allowed access.
119
+
120
+ - **Returns:**
121
+ - `boolean`: Returns `true` if the user has the required permissions, otherwise `false`.
122
+
123
+ Usage
124
+ ```
125
+ // Require vaild session or to be login to access this page
126
+ router.get(["/admin"], validateSession, checkRolePermission("SuperAdmin"), (req, res) => {
127
+ // Restricted Code
128
+ });
129
+ ```
130
+ ---
131
+
132
+ ### `validateSessionAndRole(session, userRole, requiredRoles)`
133
+ Validates both the session and the user's role permissions.
134
+
135
+ - **Parameters:**
136
+ - `session` (Object): The session object to validate.
137
+ - `userRole` (string): The role of the user.
138
+ - `requiredRoles` (optional) (string[]): An array of roles that are allowed access.
139
+
140
+ - **Returns:**
141
+ - `boolean`: Returns `true` if both the session and role permissions are valid, otherwise `false`.
142
+
143
+ Usage
144
+ ```
145
+ // Require vaild session or to be login to access this page
146
+ router.get(["/admin"], validateSessionAndRole("SuperAdmin"), (req, res) => {
147
+ // Restricted Code
148
+ });
149
+ ```
150
+ ---
151
+
152
+ ### `getUserData(session)`
153
+ Retrieves user data based on the session.
154
+
155
+ - **Parameters:**
156
+ - `session` (Object): The session object containing user information.
157
+
158
+ - **Returns:**
159
+ - `Object|null`: Returns the user data object if found, otherwise `null`.
160
+
161
+ ---
162
+
163
+ ### `authenticate(session)`
164
+ Authenticates the user by validating the session and retrieving user data.
165
+
166
+ - **Parameters:**
167
+ - `session` (Object): The session object to authenticate.
168
+
169
+ - **Returns:**
170
+ - `Object|null`: Returns the authenticated user data if successful, otherwise `null`.
171
+
172
+ Usage
173
+ ```
174
+ // Require vaild session or to be login to access this page
175
+ router.post(["/terminateAllSessions"], authenticate(mbkautheVar.Password), (req, res) => {
176
+ // Restricted Code
177
+ });
178
+ ```
179
+
180
+
181
+
85
182
  ## API Endpoints
86
183
 
87
184
  ### Login
package/docs/db.md CHANGED
@@ -35,7 +35,7 @@
35
35
  "HaveMailAccount" BOOLEAN NOT NULL DEFAULT false,
36
36
  "SessionId" TEXT,
37
37
  "GuestRole" JSONB DEFAULT '{"allowPages": [""], "NotallowPages": [""]}'::jsonb
38
- "AllowedApps" JSONB DEFAULT '{"allowPages": [""], "NotallowPages": [""]}'::jsonb
38
+ "AllowedApps" JSONB DEFAULT '["mbkauthe"]'::jsonb
39
39
  );
40
40
  ```
41
41
 
package/lib/main.js CHANGED
@@ -25,7 +25,6 @@ try {
25
25
  } catch (error) {
26
26
  console.log("Error parsing COOKIE_EXPIRE_TIME:", error);
27
27
  }
28
-
29
28
  // Enable CORS for subdomains
30
29
  router.use((req, res, next) => {
31
30
  const origin = req.headers.origin;
@@ -122,7 +121,9 @@ router.post("/mbkauthe/api/terminateAllSessions", authenticate(mbkautheVar.Main_
122
121
  req.session.destroy((err) => {
123
122
  if (err) {
124
123
  console.log("Error destroying session:", err);
125
- return res.status(500).json({ success: false, message: "Failed to terminate sessions" });
124
+ return res
125
+ .status(500)
126
+ .json({ success: false, message: "Failed to terminate sessions" });
126
127
  }
127
128
  console.log("All sessions terminated successfully");
128
129
  res.status(200).json({
@@ -184,7 +185,6 @@ router.post("/mbkauthe/api/login", async (req, res) => {
184
185
  // Query to check if the username exists
185
186
  const userQuery = `SELECT * FROM "Users" WHERE "UserName" = $1`;
186
187
  const userResult = await dblogin.query(userQuery, [username]);
187
- console.log("User query result:", userResult.rows); // Log user query result
188
188
 
189
189
  if (userResult.rows.length === 0) {
190
190
  console.log(`Username does not exist: ${username}`);
@@ -259,6 +259,15 @@ router.post("/mbkauthe/api/login", async (req, res) => {
259
259
  sessionId,
260
260
  };
261
261
 
262
+ res.cookie("sessionId", sessionId, {
263
+ maxAge: COOKIE_EXPIRE_TIME,
264
+ path: '/',
265
+ DOMAIN: mbkautheVar.IS_DEPLOYED === 'true' ? `.${mbkautheVar.DOMAIN}` : undefined,
266
+ secure: mbkautheVar.IS_DEPLOYED === 'true',
267
+ });
268
+ console.log(req.session.user);
269
+
270
+
262
271
  console.log(`User "${username}" logged in successfully`);
263
272
  res.status(200).json({
264
273
  success: true,
@@ -25,6 +25,9 @@ async function validateSession(req, res, next) {
25
25
  }
26
26
 
27
27
  if (!req.session.user) {
28
+
29
+ console.log("User not authenticated");
30
+ console.log(req.session.user);
28
31
  return res.render("templates/Error/NotLoggedIn.handlebars", {
29
32
  currentUrl: req.originalUrl,
30
33
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mbkauthe",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "description": "MBKTechStudio's reusable authentication system for Node.js applications.",
5
5
  "main": "index.js",
6
6
  "type": "module",