/**
 * This file contains methods for dealing with session tokens.
 */ import * as crypto from "crypto" ; import { promisify } from "util" ; import { toError } from "fp-ts/lib/Either" ; import { TaskEither , taskify } from "fp-ts/lib/TaskEither" ; import { EmailString , FiscalCode , NonEmptyString } from "italia-ts-commons/lib/strings" ; import { Second } from "italia-ts-commons/lib/units" ; import * as jwt from "jsonwebtoken" ; import { ulid } from "ulid" ; const asyncRandomBytes = promisify ( crypto . randomBytes ) ; export default class TokenService { /**
     * Generates a new random token.
     */ public getNewToken ( length ) { return crypto . randomBytes ( length ) . toString ( "hex" ) ; } /**
     * Generates a new random token.
     */ public getNewTokenAsync ( length ) { return asyncRandomBytes ( length ) . then ( _ => _ . toString ( "hex" ) ) ; } param privateKey param fiscalCode param tokenTtl param issuer public getJwtSupportToken ( privateKey , fiscalCode , tokenTtl , issuer ) { return taskify < Error , string > ( cb => jwt . sign ( { fiscalCode } , privateKey , { algorithm : "RS256" , expiresIn : `${ tokenTtl } seconds` , issuer , jwtid : ulid ( ) } , cb ) ) ( ) . mapLeft ( toError ) ; } param secret param name param familyName param fiscalCode param emailAddress param tokenTtl param issuer public getJwtZendeskSupportToken ( secret , name , familyName , fiscalCode , emailAddress , tokenTtl , issuer ) { return taskify < Error , string > ( cb => jwt . sign ( { email : emailAddress , external_id : fiscalCode , iat : new Date ( ) . getTime ( ) / 1000 , jti : ulid ( ) , name : `${ name } ${ familyName }` } , secret , { algorithm : "HS256" , expiresIn : `${ tokenTtl } seconds` , issuer } , cb ) ) ( ) . mapLeft ( toError ) ; } param privateKey param fiscalCode param tokenTtl param issuer param audience public getJwtMitVoucherToken ( privateKey , fiscalCode , tokenTtl , issuer , audience ) { return taskify < Error , string > ( cb => jwt . sign ( { } , privateKey , { algorithm : "ES256" , audience , expiresIn : `${ tokenTtl } seconds` , issuer , subject : fiscalCode } , cb ) ) ( ) . mapLeft ( toError ) ; } param secret param fiscalCode public getPecServerTokenHandler ( fiscalCode , secret ) { return taskify < Error , string > ( cb => jwt . sign ( { account : fiscalCode } , secret , { algorithm : "HS256" , noTimestamp : true } , cb ) ) ; } }