12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- const db = require('../config/dbConfig');
- exports.sendOtp = (req, res) => {
- const email = req.body.email;
- const otp = generateRandom4DigitNumber();
- try {
- db.query(
- 'INSERT INTO email_otp (email, otp) VALUES (?, ?) ON DUPLICATE KEY UPDATE otp = ?',
- [email, otp, otp]
- );
- } catch (error) {
- const errorMessage = {
- error: true,
- message: error.message,
- };
- return errorMessage;
- }
- // send an email using api
- res.json({ success: true, message: 'You must have received an email with otp successfully.' });
- }
- exports.validateOtp = async (req, res) => {
- const otp = req.body.otp;
- const email = req.body.email;
- const otpQuery = "SELECT * from email_otp where otp = ? and email = ?";
- const deleteOtpQuery = "DELETE from email_otp WHERE email = ?";
- db.query(otpQuery, [otp, email], (err, results) => {
- if (err) {
- console.error('Error executing query:', err);
- res.status(500).json({ success: false, message: 'Internal Server Error' });
- return;
- }
- if (results.length > 0) {
- db.query(deleteOtpQuery, [email], (err, results) => {
- res.status(200).json({ success: true, message: 'Valid OTP' });
- })
- } else {
- // OTP is invalid
- res.status(400).json({ success: false, message: 'Invalid OTP' });
- }
- });
- };
- function generateRandom4DigitNumber() {
- // Generate a random number between 1000 and 9999
- const random4DigitNumber = Math.floor(Math.random() * 9000) + 1000;
- return random4DigitNumber;
- }
|