1
1
'use strict' ;
2
2
3
- const Hashids = require ( 'hashids' ) ;
3
+ const Hashids = require ( 'hashids/cjs ' ) ;
4
4
const NODE_ENV = process . env . NODE_ENV ;
5
5
const isProduction = ( NODE_ENV === 'production' ) ;
6
6
const IGNORE_AUTH_PATH_REGEX = process . env . IGNORE_AUTH_PATH_REGEX || / ( w e b ) / ;
@@ -9,22 +9,42 @@ function isIgnoredPath(path) {
9
9
return path . search ( IGNORE_AUTH_PATH_REGEX ) >= 0 ;
10
10
}
11
11
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
+
12
23
function hashKeyMiddlewareWrapper ( options = {
13
24
salt : process . env . SALT || 'my salt' ,
14
25
hashkeyAliveTime : process . env . HASHKEY_ALIVE_TIME || 15 ,
26
+ isMainModule : false ,
15
27
} ) {
16
28
const hashSalt = options . salt ;
17
- const idHashids = new Hashids ( hashSalt , 32 , '0123456789abcdef' ) ;
18
29
// Hashkey alive time (minutes)
19
30
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
+ }
20
40
21
41
return function hashKeyMiddleware ( req , res , next ) {
22
42
if ( isIgnoredPath ( req . path ) ) {
23
43
return next ( ) ;
24
44
}
25
45
26
46
const hashKey = req . query . hashkey || req . query . access_token ;
27
- const decodedKey = idHashids . decode ( hashKey ) ;
47
+ const decodedKey = decHashId ( idHashids , hashKey ) ;
28
48
const ip = req . headers [ 'x-forwarded-for' ] || req . connection . remoteAddress ;
29
49
const err = new Error ( 'E_ACCESS_DENIED' ) ;
30
50
err . name = 'E_ACCESS_DENIED' ;
@@ -50,4 +70,13 @@ function hashKeyMiddlewareWrapper (options = {
50
70
} ;
51
71
} ;
52
72
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
+ }
0 commit comments