mdkcontroller 1.2.3 → 1.3.1

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.
@@ -1,22 +1,14 @@
1
- import child_process from "child_process";
1
+ import { decrypt, encrypt } from "./dkEncrypC.js";
2
2
 
3
- function isCalledFromNodeModules() {
4
- const error = new Error();
5
- const stackLines = error.stack.split('\n');
6
- // Bỏ qua dòng đầu tiên vì đó là thông tin của Error
7
- for (let i = 1; i < stackLines.length; i++) {
8
- if (stackLines[i].includes('node_modules')) {
9
- return true;
10
- }
11
- }
12
- return false;
13
- }
3
+ export default function () {
14
4
 
15
- export default function (db) {
16
- const tbLoginToken = db.data.loginTokens;
17
- const tbUser = db.data.users;
18
- const isModule = isCalledFromNodeModules();
19
5
  const validateBase = function name(req, res) {
6
+ const db = global.db;
7
+ db.data.loginTokens = db.data.loginTokens || [];
8
+ const tbLoginToken = db.data.loginTokens;
9
+ db.data.users = db.data.users || [];
10
+ const tbUser = db.data.users;
11
+
20
12
  const accessToken = req.cookies?.access_token;
21
13
  if (accessToken) {
22
14
  const datenow = new Date();
@@ -38,50 +30,29 @@ export default function (db) {
38
30
  }
39
31
  }
40
32
  console.log(
41
- "Module dk_modules/authorization.js: (db)=>{ validate:fn, validateBool:fn }"
33
+ "Module dk_modules/authorization.js: ()=>{ validate:fn, validateBool:fn, encrypt:fn, decrypt:fn }"
42
34
  );
43
35
  return {
44
36
  validate: (req, res, next) => {
45
37
  const resultValidate = validateBase(req, res);
46
38
  switch (resultValidate) {
47
39
  case 0:
48
- return res.status(401).json({message: 'Token không được cung cấp'});
40
+ return res.status(401).json({ message: 'Bạn cần đăng nhập trước khi thực hiện các yêu cầu đến endpoint này.' });
49
41
  case 1:
50
-
51
42
  next();
52
43
  break;
53
44
  case -1:
54
- return res.status(401).json({message: 'Token không hợp lệ'});
45
+ return res.status(401).json({ message: 'Token không hợp lệ' });
55
46
  }
56
47
  },
57
48
  validateBool: (req, res) => {
58
49
  return validateBase(req, res);
59
50
  },
60
- encrypt: async function (data = "", pw = "mdkpaswoEcrHidDefat") {
61
- const cdtoCmd = isModule ? "node_modules\\mdkcontroller\\" : "";
62
- const cmd = data + " " + pw;
63
- return new Promise((resolve, reject) => {
64
- child_process.exec(`${cdtoCmd}dk_modules\\EncryptC\\DKEncryptCMD e ${cmd}`, (error, stdout, stderr) => {
65
- if (error) {
66
- reject(error);
67
- return;
68
- }
69
- resolve(stdout.trimEnd());
70
- });
71
- });
51
+ encrypt: function (data = "", pw = "mdkpaswoEcrHidDefat") {
52
+ return encrypt(data, pw);
72
53
  },
73
54
  decrypt: function (data = "", pw = "mdkpaswoEcrHidDefat") {
74
- const cdtoCmd = isModule ? "node_modules\\mdkcontroller\\" : "";
75
- const cmd = data + " " + pw;
76
- return new Promise((resolve, reject) => {
77
- child_process.exec(`${cdtoCmd}dk_modules\\EncryptC\\DKEncryptCMD d ${cmd}`, (error, stdout, stderr) => {
78
- if (error) {
79
- reject(error);
80
- return;
81
- }
82
- resolve(stdout);
83
- });
84
- });
55
+ return decrypt(data, pw);
85
56
  }
86
57
  }
87
58
  };
@@ -1,23 +1,23 @@
1
- export default (db) => {
1
+
2
+
3
+ export const getNumber = (name) => {
4
+ const db = global.db;
5
+ db.data.autoSequenceNumber = db.data.autoSequenceNumber || [];
2
6
  const tbSequence = db.data.autoSequenceNumber;
7
+ let continueNumber = tbSequence.find(f => f.name == name);
8
+ if (!continueNumber) {
9
+ tbSequence
10
+ .push({
11
+ name: name,
12
+ currentNumber: 0
13
+ });
14
+ continueNumber = tbSequence.find(f => f.name == name);
15
+ }
16
+ continueNumber.currentNumber += 1
17
+ db.write();
18
+ return continueNumber.currentNumber;
19
+ };
3
20
 
4
- console.log(
5
- "Module dk_modules/autoSequence.js: (db)=>{ getNumber:fn }"
6
- );
7
- return {
8
- getNumber: (name) => {
9
- let continueNumber = tbSequence.find(f => f.name == name);
10
- if (!continueNumber) {
11
- tbSequence
12
- .push({
13
- name: name,
14
- currentNumber: 0
15
- });
16
- continueNumber = tbSequence.find(f => f.name == name);
17
- }
18
- continueNumber.currentNumber += 1
19
- db.write();
20
- return continueNumber.currentNumber;
21
- }
22
- };
23
- }
21
+ console.log(
22
+ "Module dk_modules/autoSequence.js: ()=> getNumber:fn"
23
+ );
@@ -0,0 +1,33 @@
1
+ import crypto from 'crypto';
2
+
3
+ function normalizeKey32(inputKey) {
4
+ const length = 32;
5
+ if (inputKey.length > length) {
6
+ return inputKey.slice(0, length); // Cắt bớt nếu quá dài
7
+ }
8
+ return inputKey.padEnd(length, '0'); // Thêm '0' vào cuối nếu quá ngắn
9
+ }
10
+
11
+ export const encrypt = (text, keyTextMAX32) => {
12
+ const key = Buffer.from(normalizeKey32(keyTextMAX32), 'utf8');
13
+ const iv = crypto.randomBytes(16); // Vector khởi tạo
14
+ const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key, 'hex'), iv);
15
+ let encrypted = cipher.update(text, 'utf8', 'hex');
16
+ encrypted += cipher.final('hex');
17
+ return iv.toString('hex') + encrypted;
18
+ }
19
+
20
+ export const decrypt = (encryptedText, keyTextMAX32) => {
21
+ const key = Buffer.from(normalizeKey32(keyTextMAX32), 'utf8');
22
+ const iv = Buffer.from(encryptedText.slice(0, 32), 'hex');
23
+ const encryptedData = encryptedText.slice(32);
24
+ const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key, 'hex'), iv);
25
+ let decrypted = decipher.update(encryptedData, 'hex', 'utf8');
26
+ decrypted += decipher.final('utf8');
27
+ return decrypted;
28
+ }
29
+
30
+
31
+ console.log(
32
+ "Module dk_modules/authorization.js: { encrypt:fn, decrypt:fn }"
33
+ );
@@ -1,23 +1,25 @@
1
+ import { console } from "inspector";
1
2
  import authInstant from "./authorization.js";
2
- import autoSequenceInstant from "./autoSequence.js";
3
- import {generateRandomToken, privateKey} from "./dkvar.js";
3
+ import { getNumber } from "./autoSequence.js";
4
4
 
5
5
  export default (router, db) => {
6
6
 
7
- const auth = authInstant(db);
8
- const autoNumber = autoSequenceInstant(db);
7
+ const auth = authInstant();
8
+
9
+ db.data.users = db.data.users || [];
9
10
  const tbUser = db.data.users;
11
+ db.data.loginTokens = db.data.loginTokens || [];
10
12
  const tbLoginToken = db.data.loginTokens;
11
13
 
12
14
 
13
15
  router.get("/users/gets", auth.validate, (req, res) => {
14
- res.json({message: "Get all users"});
16
+ res.json({ message: "Get all users" });
15
17
  });
16
18
 
17
19
  router.get("/users/get", auth.validate, (req, res) => {
18
20
  const userId = req.params.id;
19
- const userO = tbUser.find({id: parseInt(userId)});
20
- res.json({message: `Get user with ID ${userId}`, user: userO});
21
+ const userO = tbUser.find({ id: parseInt(userId) });
22
+ res.json({ message: `Get user with ID ${userId}`, user: userO });
21
23
  });
22
24
  router.get('/users/logout', async (req, res) => {
23
25
  const accessToken = req.cookies?.access_token;
@@ -26,7 +28,7 @@ export default (router, db) => {
26
28
  tbLoginToken.slice(indexToken, 1);
27
29
  await db.write();
28
30
  }
29
- res.clearCookie('access_token', {httpOnly: true});
31
+ res.clearCookie('access_token', { httpOnly: true });
30
32
  res.clearCookie('sessionUExt', {});
31
33
  res.redirect('/login');
32
34
  });
@@ -34,29 +36,30 @@ export default (router, db) => {
34
36
  router.post("/users/login", async (req, res) => {
35
37
  const bodyParser = req.body;
36
38
  if (bodyParser.userName && bodyParser.password) {
37
- let userLoging = tbUser.find(f => f.userName == bodyParser.userName.toLowerCase() && f.password == bodyParser.password);
39
+
40
+ let userLoging = tbUser.find(f => f.userName == bodyParser.userName.toLowerCase().trim() && auth.decrypt(f.password) == bodyParser.password);
38
41
  if (userLoging) {
39
- const userIdCode = await auth.encrypt(userLoging.userName);
40
- const accessToken = userIdCode + generateRandomToken(100);
42
+ const userIdCode = auth.encrypt(userLoging.userName);
43
+ const accessToken = userIdCode + global.generateRandomString(100);
41
44
 
42
45
  const expiredValue = new Date();
43
46
  expiredValue.setMonth(expiredValue.getMonth() + 1);
44
47
 
45
48
  tbLoginToken.push({
46
- id: autoNumber.getNumber('loginTokens'),
49
+ id: getNumber('loginTokens'),
47
50
  userId: userLoging.id,
48
51
  tokenString: accessToken,
49
52
  expired: expiredValue
50
53
  });
51
54
  await db.write();
52
- res.cookie('access_token', accessToken, {httpOnly: true, expires: expiredValue});
53
- res.cookie('sessionUExt', userIdCode, {expires: expiredValue});
54
- res.json({message: `Đăng nhập thành công.`, success: true});
55
+ res.cookie('access_token', accessToken, { httpOnly: true, expires: expiredValue });
56
+ res.cookie('sessionUExt', userIdCode, { expires: expiredValue });
57
+ res.json({ message: `Đăng nhập thành công.`, success: true });
55
58
  } else {
56
- res.json({message: `Tài khoản hoặc mật khẩu không chính xác.`, success: false});
59
+ res.json({ message: `Tài khoản hoặc mật khẩu không chính xác.`, success: false });
57
60
  }
58
61
  } else {
59
- res.json({message: `Không đủ thông tin để đăng nhập.`, success: false});
62
+ res.json({ message: `Không đủ thông tin để đăng nhập.`, success: false });
60
63
  }
61
64
  });
62
65
  router.get("/users/tryGetAccess", (req, res) => {
@@ -65,13 +68,13 @@ export default (router, db) => {
65
68
  const accessToken = req.cookies?.access_token;
66
69
  const expiredValue = new Date();
67
70
  expiredValue.setMonth(expiredValue.getMonth() + 1);
68
- res.cookie('access_token', accessToken, {httpOnly: true, expires: expiredValue});
71
+ res.cookie('access_token', accessToken, { httpOnly: true, expires: expiredValue });
69
72
  }
70
- res.json({success: true, isLogin: isLogin});
73
+ res.json({ success: true, isLogin: isLogin });
71
74
  });
72
75
  router.post("/users/create", async (req, res) => {
73
76
  if (!global.allowRegister) {
74
- res.json({message: `Chức năng đăng ký tài khoản mới không được cung cấp.`, success: false});
77
+ res.json({ message: `Chức năng đăng ký tài khoản mới không được cung cấp.`, success: false });
75
78
  return;
76
79
  }
77
80
  const bodyParser = req.body;
@@ -80,15 +83,15 @@ export default (router, db) => {
80
83
  if (!newUser) {
81
84
  let validateUserName = tbUser.find(f => f.userName == bodyParser.userName.toLowerCase());
82
85
  if (validateUserName) {
83
- res.json({message: `Tên tài khoản đã có người đăng ký.`, success: false});
86
+ res.json({ message: `Tên tài khoản đã có người đăng ký.`, success: false });
84
87
  return;
85
88
  }
86
89
  tbUser
87
90
  .push({
88
- id: autoNumber.getNumber('users'),
91
+ id: getNumber('users'),
89
92
  userName: bodyParser.userName.toLowerCase(),
90
93
  email: bodyParser.email.toLowerCase(),
91
- password: bodyParser.password,
94
+ password: auth.encrypt(bodyParser.password),
92
95
  active: true,
93
96
  amount: 0
94
97
  });
@@ -107,14 +110,14 @@ export default (router, db) => {
107
110
  });
108
111
  }
109
112
  } else {
110
- res.json({message: `Không đủ thông tin để tạo User mới.`, success: false});
113
+ res.json({ message: `Không đủ thông tin để tạo User mới.`, success: false });
111
114
  }
112
115
  });
113
116
 
114
117
  console.log(
115
118
  "Module dk_modules/users.js: (db)=>{ router: router, table: tbUser }"
116
119
  );
117
- return {router: router, table: tbUser};
120
+ return { router: router, table: tbUser };
118
121
  };
119
122
 
120
123
  // // Thêm một người dùng mới
package/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import main from "./main.js"
2
2
  import authen from "./dk_modules/authorization.js"
3
- import ause from "./dk_modules/autoSequence.js"
3
+ import { getNumber } from "./dk_modules/autoSequence.js"
4
4
 
5
5
  export const Root = async (a, b) => await main(a, b);
6
- export const Authen = (db) => authen(db);
7
- export const Sequense = (db) => ause(db);
6
+ export const Authen = () => authen();
7
+ export const Sequense = (key) => {
8
+ return getNumber(key);
9
+ }
package/main.js CHANGED
@@ -12,7 +12,6 @@ import authInstant from "./dk_modules/authorization.js";
12
12
 
13
13
  import {fileURLToPath} from "url";
14
14
  import path from 'path';
15
- // import {privateKey, encodeMini} from "./dk_modules/dkvar.js";
16
15
 
17
16
  export default async function (appname, cfgHandler = {}) {
18
17
 
@@ -22,7 +21,7 @@ export default async function (appname, cfgHandler = {}) {
22
21
  const app = express();
23
22
  const server = createServer(app);
24
23
  const db = await dbInstant(appname + "-Database.json");
25
- const auth = authInstant(db);
24
+ const auth = authInstant();
26
25
  const userRoutes = userInstant(Router(), db);
27
26
 
28
27
  app.use(json());
package/package.json CHANGED
@@ -1,24 +1,19 @@
1
1
  {
2
2
  "dependencies": {
3
- "child_process": "^1.0.2",
4
3
  "cookie-parser": "^1.4.6",
5
4
  "express": "^4.18.2",
6
- "fluent-ffmpeg": "^2.1.2",
7
- "handlebars": "^4.7.8",
8
- "js-yaml": "^4.1.0",
9
5
  "lowdb": "^7.0.1",
10
6
  "socket.io": "^4.7.2"
11
7
  },
12
8
  "name": "mdkcontroller",
13
- "version": "1.2.3",
9
+ "version": "1.3.1",
14
10
  "keywords": [],
15
11
  "author": "KHANHNBD <khanh272421@gmail.com>",
16
12
  "license": "ISC",
17
13
  "description": "Quick setup authentication and express",
18
14
  "type": "module",
19
15
  "exports": {
20
- ".": "./index.js",
21
- "./autosequence": "./dk_modules/autoSequence.js"
16
+ ".": "./index.js"
22
17
  },
23
18
  "types": "./index.js",
24
19
  "files": [
@@ -1,23 +0,0 @@
1
- {
2
- "runtimeTarget": {
3
- "name": ".NETCoreApp,Version=v7.0",
4
- "signature": ""
5
- },
6
- "compilationOptions": {},
7
- "targets": {
8
- ".NETCoreApp,Version=v7.0": {
9
- "DKEncryptCMD/1.0.0": {
10
- "runtime": {
11
- "DKEncryptCMD.dll": {}
12
- }
13
- }
14
- }
15
- },
16
- "libraries": {
17
- "DKEncryptCMD/1.0.0": {
18
- "type": "project",
19
- "serviceable": false,
20
- "sha512": ""
21
- }
22
- }
23
- }
@@ -1,9 +0,0 @@
1
- {
2
- "runtimeOptions": {
3
- "tfm": "net7.0",
4
- "framework": {
5
- "name": "Microsoft.NETCore.App",
6
- "version": "7.0.0"
7
- }
8
- }
9
- }
@@ -1,13 +0,0 @@
1
- import {Buffer} from 'node:buffer';
2
-
3
- export const privateKey = 'eyJzdWIiOiI5Nzc4IiwibmFtZSI6IkRraGFuaE1NTSIsImlhdCI6ODkxMDB9';
4
-
5
- export function generateRandomToken(length = 100) {
6
- const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
7
- let token = '';
8
- for (let i = 0; i < length; i++) {
9
- const randomIndex = Math.floor(Math.random() * characters.length);
10
- token += characters.charAt(randomIndex);
11
- }
12
- return token;
13
- }