const passwordFields = ['password', 'secret', 'secretkey']
const cardFields = ['cardnumber', 'cvc', 'authenticationcode', 'authorizationcode']
class MaskHelperClass {
maskFields: (json: Object) => any = json => {
this.deepReplace(json, passwordFields, this.maskPassword)
this.deepReplace(json, cardFields, this.maskCardNumber)
return json
}
maskPassword: (password: string) => string = password => {
const maskPasswordLength = password.length > 16 ? 16 : password.length
return `*`.repeat(maskPasswordLength)
}
maskCardNumber: (card: string) => string = card => {
card = (card + '').trim()
const options = {
maskWith: '*',
unmaskedStartDigits: 6,
unmaskedEndDigits: 4,
}
if (options.unmaskedStartDigits + options.unmaskedEndDigits >= card.length) {
return '*'.repeat(card.length)
}
let maskedCard = ''
for (let i = 0; i < options.unmaskedStartDigits; i++) {
maskedCard += card[i]
}
for (let i = options.unmaskedStartDigits; i < card.length - options.unmaskedEndDigits; i++) {
if (isNaN(parseInt(card[i]))) {
maskedCard += card[i]
} else {
maskedCard += options.maskWith
}
}
for (let i = card.length - options.unmaskedEndDigits; i < card.length; i++) {
maskedCard += card[i]
}
return maskedCard
}
deepReplace = (x: any, targetKeys: string[], replaceWith: (v: any) => any) => {
if (Array.isArray(x)) {
x.forEach(x => this.deepReplace(x, targetKeys, replaceWith))
} else if (typeof x === 'object') {
for (const key in x) {
if (targetKeys.includes(key.toLowerCase())) x[key] = replaceWith(x[key])
if (typeof x[key] === 'object') {
this.deepReplace(x[key], targetKeys, replaceWith)
}
}
}
}
maskPhoneNumber = (phoneNumber: string): string => {
if (typeof phoneNumber !== 'string' || phoneNumber.length === 0) {
return phoneNumber
}
const numToMask: number = Math.min(5, phoneNumber.length)
const middleMasked: string = '*'.repeat(numToMask)
const firstMasked: string = phoneNumber.substring(0, numToMask - 1)
const lastMasked: string = phoneNumber.substring(9)
return firstMasked + middleMasked + lastMasked
}
}
const MaskHelper = new MaskHelperClass()
export default MaskHelper