Skip to content

Commit b152a61

Browse files
committed
Update index.js and package
1 parent 532dbc5 commit b152a61

File tree

3 files changed

+37
-8
lines changed

3 files changed

+37
-8
lines changed

index.js

+33-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict';
22

3-
const Hashids = require('hashids');
3+
const Hashids = require('hashids/cjs');
44
const NODE_ENV = process.env.NODE_ENV;
55
const isProduction = (NODE_ENV === 'production');
66
const IGNORE_AUTH_PATH_REGEX = process.env.IGNORE_AUTH_PATH_REGEX || /(web)/;
@@ -9,22 +9,42 @@ function isIgnoredPath(path) {
99
return path.search(IGNORE_AUTH_PATH_REGEX) >= 0;
1010
}
1111

12+
function genHashId(idHashids, id = 141236) {
13+
const time = Date.now(); // Timestamp
14+
const idHash = idHashids.encode([id, time]); // encode id and time to fake hex
15+
return idHash;
16+
}
17+
18+
function decHashId(idHashids, encrypted) {
19+
const decoded = idHashids.decode(encrypted);
20+
return decoded;
21+
}
22+
1223
function hashKeyMiddlewareWrapper (options = {
1324
salt: process.env.SALT || 'my salt',
1425
hashkeyAliveTime: process.env.HASHKEY_ALIVE_TIME || 15,
26+
isMainModule: false,
1527
}) {
1628
const hashSalt = options.salt;
17-
const idHashids = new Hashids(hashSalt, 32, '0123456789abcdef');
1829
// Hashkey alive time (minutes)
1930
const HASHKEY_ALIVE_TIME = options.hashkeyAliveTime * 60 * 1000;
31+
const idHashids = new Hashids(hashSalt, 32, '0123456789abcdef');
32+
33+
if (options.isMainModule === true) {
34+
const hashid = genHashId(idHashids, process.argv[2]);
35+
return {
36+
hashid,
37+
decoded: decHashId(idHashids, hashid),
38+
};
39+
}
2040

2141
return function hashKeyMiddleware(req, res, next) {
2242
if (isIgnoredPath(req.path)) {
2343
return next();
2444
}
2545

2646
const hashKey = req.query.hashkey || req.query.access_token;
27-
const decodedKey = idHashids.decode(hashKey);
47+
const decodedKey = decHashId(idHashids, hashKey);
2848
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
2949
const err = new Error('E_ACCESS_DENIED');
3050
err.name = 'E_ACCESS_DENIED';
@@ -50,4 +70,13 @@ function hashKeyMiddlewareWrapper (options = {
5070
};
5171
};
5272

53-
module.exports = hashKeyMiddlewareWrapper;
73+
if (require.main === module) {
74+
const hashid = hashKeyMiddlewareWrapper({
75+
salt: process.env.SALT,
76+
isMainModule: true,
77+
});
78+
79+
console.log(hashid);
80+
} else {
81+
module.exports = hashKeyMiddlewareWrapper;
82+
}

package-lock.json

+3-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@
1010
"author": "",
1111
"license": "ISC",
1212
"dependencies": {
13-
"hashids": "^1.2.2"
13+
"hashids": "^2.1.0"
1414
}
1515
}

0 commit comments

Comments
 (0)