emailController.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const db = require('../config/dbConfig');
  2. exports.sendOtp = (req, res) => {
  3. const email = req.body.email;
  4. const otp = generateRandom4DigitNumber();
  5. try {
  6. db.query(
  7. 'INSERT INTO email_otp (email, otp) VALUES (?, ?) ON DUPLICATE KEY UPDATE otp = ?',
  8. [email, otp, otp]
  9. );
  10. } catch (error) {
  11. const errorMessage = {
  12. error: true,
  13. message: error.message,
  14. };
  15. return errorMessage;
  16. }
  17. // send an email using api
  18. res.json({ success: true, message: 'You must have received an email with otp successfully.' });
  19. }
  20. exports.validateOtp = async (req, res) => {
  21. const otp = req.body.otp;
  22. const email = req.body.email;
  23. const otpQuery = "SELECT * from email_otp where otp = ? and email = ?";
  24. const deleteOtpQuery = "DELETE from email_otp WHERE email = ?";
  25. db.query(otpQuery, [otp, email], (err, results) => {
  26. if (err) {
  27. console.error('Error executing query:', err);
  28. res.status(500).json({ success: false, message: 'Internal Server Error' });
  29. return;
  30. }
  31. if (results.length > 0) {
  32. db.query(deleteOtpQuery, [email], (err, results) => {
  33. res.status(200).json({ success: true, message: 'Valid OTP' });
  34. })
  35. } else {
  36. // OTP is invalid
  37. res.status(400).json({ success: false, message: 'Invalid OTP' });
  38. }
  39. });
  40. };
  41. function generateRandom4DigitNumber() {
  42. // Generate a random number between 1000 and 9999
  43. const random4DigitNumber = Math.floor(Math.random() * 9000) + 1000;
  44. return random4DigitNumber;
  45. }