"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OtpService = void 0; const common_1 = require("@nestjs/common"); const otplib_1 = require("otplib"); const prisma_service_1 = require("../prisma/prisma.service"); const axios_1 = __importDefault(require("axios")); const QRCode = __importStar(require("qrcode")); let OtpService = class OtpService { prisma; emailOtpStore = new Map(); whatsappOtpStore = new Map(); constructor(prisma) { this.prisma = prisma; } async sendEmailOtp(userId) { const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) { throw new common_1.BadRequestException('User not found'); } const code = this.generateOtpCode(); const expiresAt = new Date(Date.now() + 10 * 60 * 1000); this.emailOtpStore.set(userId, { code, expiresAt }); try { await this.sendOtpViaWebhook(user.email, code); return { success: true, message: 'OTP sent to your email' }; } catch (error) { console.error('Failed to send OTP via webhook:', error); console.log(`📧 OTP Code for ${user.email}: ${code}`); return { success: true, message: 'OTP sent (check console for dev code)', }; } } verifyEmailOtpForLogin(userId, code) { const stored = this.emailOtpStore.get(userId); if (!stored) { return false; } if (new Date() > stored.expiresAt) { this.emailOtpStore.delete(userId); return false; } if (stored.code !== code) { return false; } this.emailOtpStore.delete(userId); return true; } async verifyEmailOtp(userId, code) { const stored = this.emailOtpStore.get(userId); if (!stored) { throw new common_1.BadRequestException('No OTP found. Please request a new one.'); } if (new Date() > stored.expiresAt) { this.emailOtpStore.delete(userId); throw new common_1.BadRequestException('OTP has expired. Please request a new one.'); } if (stored.code !== code) { throw new common_1.BadRequestException('Invalid OTP code.'); } await this.prisma.user.update({ where: { id: userId }, data: { otpEmailEnabled: true }, }); this.emailOtpStore.delete(userId); return { success: true, message: 'Email OTP enabled successfully' }; } async disableEmailOtp(userId) { await this.prisma.user.update({ where: { id: userId }, data: { otpEmailEnabled: false }, }); return { success: true, message: 'Email OTP disabled' }; } async setupTotp(userId) { const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) { throw new common_1.BadRequestException('User not found'); } const secret = otplib_1.authenticator.generateSecret(); await this.prisma.user.update({ where: { id: userId }, data: { otpTotpSecret: secret }, }); const serviceName = 'Tabungin'; const accountName = user.email; const otpauthUrl = otplib_1.authenticator.keyuri(accountName, serviceName, secret); const qrCodeDataUrl = await QRCode.toDataURL(otpauthUrl); return { secret, qrCode: qrCodeDataUrl, }; } async verifyTotp(userId, code) { const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { otpTotpSecret: true }, }); if (!user?.otpTotpSecret) { throw new common_1.BadRequestException('No TOTP setup found. Please setup TOTP first.'); } const isValid = otplib_1.authenticator.verify({ token: code, secret: user.otpTotpSecret, }); if (!isValid) { throw new common_1.BadRequestException('Invalid TOTP code.'); } await this.prisma.user.update({ where: { id: userId }, data: { otpTotpEnabled: true }, }); return { success: true, message: 'TOTP enabled successfully' }; } async disableTotp(userId) { await this.prisma.user.update({ where: { id: userId }, data: { otpTotpEnabled: false, otpTotpSecret: null, }, }); return { success: true, message: 'TOTP disabled' }; } async getStatus(userId) { const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { phone: true, otpEmailEnabled: true, otpWhatsappEnabled: true, otpTotpEnabled: true, otpTotpSecret: true, }, }); if (!user) { return { emailEnabled: false, whatsappEnabled: false, totpEnabled: false, }; } return { phone: user.phone, emailEnabled: user.otpEmailEnabled, whatsappEnabled: user.otpWhatsappEnabled, totpEnabled: user.otpTotpEnabled, totpSecret: user.otpTotpSecret, }; } async verifyOtpGate(userId, code, method) { const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { otpEmailEnabled: true, otpTotpEnabled: true, otpTotpSecret: true, }, }); if (!user) { return false; } if (method === 'email' && user.otpEmailEnabled) { const stored = this.emailOtpStore.get(userId); if (stored && new Date() <= stored.expiresAt && stored.code === code) { return true; } } if (method === 'totp' && user.otpTotpEnabled && user.otpTotpSecret) { return otplib_1.authenticator.verify({ token: code, secret: user.otpTotpSecret }); } return false; } generateOtpCode() { return Math.floor(100000 + Math.random() * 900000).toString(); } async sendOtpViaWebhook(email, code, mode = 'test') { const webhookUrl = process.env.OTP_SEND_WEBHOOK_URL_TEST || process.env.OTP_SEND_WEBHOOK_URL; if (!webhookUrl) { throw new Error('OTP_SEND_WEBHOOK_URL or OTP_SEND_WEBHOOK_URL_TEST not configured'); } await axios_1.default.post(webhookUrl, { method: 'email', mode, to: email, subject: 'Tabungin - Your OTP Code', message: `Your OTP code is: ${code}. This code will expire in 10 minutes.`, code, }); } async sendWhatsappOtp(userId, mode = 'test') { const user = await this.prisma.user.findUnique({ where: { id: userId } }); if (!user) { throw new common_1.BadRequestException('User not found'); } if (!user.phone) { throw new common_1.BadRequestException('Phone number not set'); } const code = this.generateOtpCode(); const expiresAt = new Date(Date.now() + 10 * 60 * 1000); this.whatsappOtpStore.set(userId, { code, expiresAt }); try { await this.sendWhatsappOtpViaWebhook(user.phone, code, mode); return { success: true, message: 'OTP sent to your WhatsApp' }; } catch (error) { console.error('Failed to send WhatsApp OTP via webhook:', error); console.log(`📱 WhatsApp OTP Code for ${user.phone}: ${code}`); return { success: true, message: 'OTP sent (check console for dev code)', }; } } async verifyWhatsappOtp(userId, code) { const stored = this.whatsappOtpStore.get(userId); if (!stored) { throw new common_1.BadRequestException('No OTP found. Please request a new one.'); } if (new Date() > stored.expiresAt) { this.whatsappOtpStore.delete(userId); throw new common_1.BadRequestException('OTP has expired. Please request a new one.'); } if (stored.code !== code) { throw new common_1.BadRequestException('Invalid OTP code'); } await this.prisma.user.update({ where: { id: userId }, data: { otpWhatsappEnabled: true }, }); this.whatsappOtpStore.delete(userId); return { success: true, message: 'WhatsApp OTP enabled successfully' }; } verifyWhatsappOtpForLogin(userId, code) { const stored = this.whatsappOtpStore.get(userId); if (!stored) { return false; } if (new Date() > stored.expiresAt) { this.whatsappOtpStore.delete(userId); return false; } if (stored.code !== code) { return false; } this.whatsappOtpStore.delete(userId); return true; } async disableWhatsappOtp(userId) { await this.prisma.user.update({ where: { id: userId }, data: { otpWhatsappEnabled: false }, }); return { success: true, message: 'WhatsApp OTP disabled' }; } async checkWhatsappNumber(phone) { try { const webhookUrl = process.env.OTP_SEND_WEBHOOK_URL_TEST || process.env.OTP_SEND_WEBHOOK_URL; if (!webhookUrl) { throw new Error('Webhook URL not configured'); } const response = await axios_1.default.post(webhookUrl, { method: 'whatsapp', mode: 'checknumber', phone, }); return { success: true, isRegistered: response.data?.isRegistered || false, message: response.data?.message || 'Number checked', }; } catch (error) { console.error('Failed to check WhatsApp number:', error); console.log(`📱 Checking WhatsApp number: ${phone} - Assumed valid`); return { success: true, isRegistered: true, message: 'Number is valid (dev mode)', }; } } async sendWhatsappOtpViaWebhook(phone, code, mode = 'test') { const webhookUrl = process.env.OTP_SEND_WEBHOOK_URL_TEST || process.env.OTP_SEND_WEBHOOK_URL; if (!webhookUrl) { throw new Error('Webhook URL not configured'); } await axios_1.default.post(webhookUrl, { method: 'whatsapp', mode, phone, message: `Your Tabungin OTP code is: ${code}. This code will expire in 10 minutes.`, code, }); } }; exports.OtpService = OtpService; exports.OtpService = OtpService = __decorate([ (0, common_1.Injectable)(), __metadata("design:paramtypes", [prisma_service_1.PrismaService]) ], OtpService); //# sourceMappingURL=otp.service.js.map