import { $log } from '@tsed/logger' ; import * as crypto from 'crypto' ; import { ChallengeService } from './ChallengeService' ; export class BlockReorderingService extends ChallengeService { static KEY = "aneuck27sSi2m3b$" ; public static createToken ( username , isAdmin = false ) { const tokenContent = `username=${ username };isAdmin=${ isAdmin };at=${ new Date ( ) . toUTCString ( ) }` ; const encrypted = this . encryptToken ( tokenContent ) ; $log . info ( "Generated token: " + tokenContent ) ; $log . info ( "Encrypted anonymous token " + encrypted ) ; return encrypted ; } public static encryptToken ( token ) { const cipher = crypto . createCipheriv ( 'aes-128-ecb' , Buffer . from ( BlockReorderingService . KEY ) , '' ) ; const tokenBuffer = Buffer . from ( token , 'utf8' ) ; let encrypted = cipher . update ( tokenBuffer ) ; encrypted = Buffer . concat ( [ encrypted , cipher . final ( ) ] ) ; return encrypted . toString ( "hex" ) ; } public static decryptToken ( token ) { const decipher = crypto . createDecipheriv ( 'aes-128-ecb' , Buffer . from ( BlockReorderingService . KEY ) , '' ) ; const encryptedText = Buffer . from ( token , 'hex' ) ; let decrypted = decipher . update ( encryptedText ) ; decrypted = Buffer . concat ( [ decrypted , decipher . final ( ) ] ) ; const t = decrypted . toString ( ) ; $log . info ( "Decrypted token: " + t ) ; return t ; } public static isAdmin ( token ) { $log . info ( "Decrypting token " + token ) ; const tokenObj = { } ; const decryptedToken = this . decryptToken ( token ) ; const tokenPars = decryptedToken . split ( ";" ) ; tokenPars . forEach ( p => { const tmp = p . split ( "=" ) ; const key = tmp [ 0 ] ; const value = tmp [ 1 ] ; tokenObj [ key ] = value ; } ) ; return tokenObj . isAdmin === 'true' ; } }