import * as jwt from 'jsonwebtoken' ; import { cipher , util } from 'node-forge' ; import { config } from '../config' ; export function decryptData ( encryptedData , iv , sessionKey ) { const encryptedDataNew = Buffer . from ( encryptedData , 'base64' ) ; const sessionKeyNew = Buffer . from ( sessionKey , 'base64' ) ; const ivNew = Buffer . from ( iv , 'base64' ) ; let decoded ; try { const decipher = cipher . createDecipher ( 'AES-CBC' , new util . ByteStringBuffer ( sessionKeyNew ) ) ; decipher . start ( { iv : new util . ByteStringBuffer ( ivNew ) } ) ; decipher . update ( new util . ByteStringBuffer ( encryptedDataNew ) ) ; decipher . finish ( ) ; decoded = JSON . parse ( decipher . output . toString ( ) ) ; } catch ( err ) { throw new Error ( 'Illegal Buffer' ) ; } if ( decoded . watermark . appid !== config . wxAppid ) { throw new Error ( 'Illegal Buffer' ) ; } return decoded ; } export function sign ( id , isGuest = true ) { const options = { } ; options . expiresIn = isGuest ? '1d' : config . expiresIn ; return jwt . sign ( { id } , config . jwtSecret , options ) ; } export function verify ( token ) { const data = jwt . verify ( token . startsWith ( 'Bearer ' ) ? token . slice ( 7 ) : token , config . jwtSecret ) ; if ( typeof data === 'string' ) { return Number ( data ) ; } return data [ 'id' ] ; }