otpauth
otpauth copied to clipboard
getting null when validate with token can any oine help me to find what exactly issue
generateRandomBase32 = () => {
const buffer = crypto.randomBytes(15);
const base32 = encode(buffer).replace(/=/g, '').substring(0, 24);
return base32;
};
totpGenerate(secret: string): OTPAuth.TOTP {
const totp = new OTPAuth.TOTP({
issuer: Config.ISSUER,
label: Config.LABEL,
algorithm: Config.ALGORITHM,
digits: Number(Config.DIGIT),
period: Number(Config.PERIOD),
secret: secret,
});
return totp;
}
async enable2FA(towFAEnableDto: TowFAEnableDto) {
try {
const user = await this.userRepository.find({
uuid: towFAEnableDto.userUuid,
});
if (!user) {
throw new NotFoundException('User Not found');
}
const secret = this.generateRandomBase32();
/**
* TOTP: Time-based One-time Password
*/
const totp = this.totpGenerate(secret);
const url = totp.toString();
const payload = await this.towFARepository.createOrUpdate(user.uuid, {
appAuthUrl: url,
secret: secret,
enable: towFAEnableDto.enable,
authType: towFAEnableDto.authType,
});
return payload;
} catch (error) {
throw errorHandler(error);
}
}
async login2fa({ userUuid, token }: Login2faDto) {
try {
let user: any = await this.userRepository.find({
uuid: userUuid,
softDelete: false,
});
user = this.exclude(user, ['password']);
if (!user) {
throw new NotFoundException('Invalid user');
}
const totp = this.totpGenerate(user.towFa.secret);
// const t = totp.generate();
const delta = totp.validate({ token });
if (delta === null) throw new NotFoundException('Invalid OTP');
return true;
} catch (error) {
throw errorHandler(error);
}
}