11'use strict' ;
22
3- const Hashids = require ( 'hashids' ) ;
3+ const Hashids = require ( 'hashids/cjs ' ) ;
44const NODE_ENV = process . env . NODE_ENV ;
55const isProduction = ( NODE_ENV === 'production' ) ;
66const IGNORE_AUTH_PATH_REGEX = process . env . IGNORE_AUTH_PATH_REGEX || / ( w e b ) / ;
@@ -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+
1223function 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+ }
0 commit comments