emailController.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. const db = require('../config/dbConfig');
  2. const transporter = require('../config/emailConfig');
  3. const mailOptions = {
  4. from: 'your-email@example.com', // Replace with your email address
  5. to: 'recipient@example.com', // Replace with the recipient's email address
  6. subject: 'OTP to login',
  7. text: 'Body of the email'
  8. };
  9. exports.sendOtp = (req, res) => {
  10. const email = req.body.email;
  11. const otp = generateRandom4DigitNumber();
  12. db.query(
  13. 'INSERT INTO email_otp (email, otp) VALUES (?, ?) ON DUPLICATE KEY UPDATE otp = ?',
  14. [email, otp, otp],
  15. (err, results) => {
  16. if (err) {
  17. console.error('Error executing query:', err);
  18. res.status(500).json({ success: false, message: 'Internal Server Error' });
  19. return;
  20. }
  21. sendMail(otp, email, req, res);
  22. }
  23. );
  24. }
  25. exports.validateOtp = async (req, res) => {
  26. const otp = req.body.otp;
  27. const email = req.body.email;
  28. const otpQuery = "SELECT * from email_otp where otp = ? and email = ?";
  29. const deleteOtpQuery = "DELETE from email_otp WHERE email = ?";
  30. db.query(otpQuery, [otp, email], (err, results) => {
  31. if (err) {
  32. console.error('Error executing query:', err);
  33. res.status(500).json({ success: false, message: 'Internal Server Error' });
  34. return;
  35. }
  36. if (results.length > 0) {
  37. db.query(deleteOtpQuery, [email], (err, results) => {
  38. res.status(200).json({ success: true, message: 'Valid OTP' });
  39. })
  40. } else {
  41. // OTP is invalid
  42. res.status(400).json({ success: false, message: 'Invalid OTP' });
  43. }
  44. });
  45. };
  46. function sendMail(otp, email, req, res) {
  47. const mailOptions = {
  48. from: 'hello@communityrule.info', // Replace with your email address
  49. to: email, // Replace with the recipient's email address
  50. subject: 'Login code for commnunityRule',
  51. text: 'Login code for CommunityRule: ' + otp,
  52. };
  53. transporter.sendMail(mailOptions, (error, info) => {
  54. if (error) {
  55. console.error('Error:', error);
  56. req.status(500).json({ success: false, message: 'Internal Server Error' });
  57. return;
  58. }
  59. res.json({ success: true, message: 'You must have received an email with otp successfully.' });
  60. });
  61. }
  62. function generateRandom4DigitNumber() {
  63. // Generate a random number between 1000 and 9999
  64. const random4DigitNumber = Math.floor(Math.random() * 9000) + 1000;
  65. return random4DigitNumber;
  66. }