emailController.js 2.5 KB

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