emailVerification.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const Merchant = require("../models/merchant.js");
  2. const mailgun = require("mailgun-js")({apiKey: process.env.MG_SUBLINE_APIKEY, domain: "mail.thesubline.net"});
  3. const VerifyEmail = require("../emails/verifyEmail.js");
  4. module.exports = {
  5. sendVerifyEmail: function(req, res){
  6. Merchant.findOne({_id: req.params.id})
  7. .then((merchant)=>{
  8. const mailgunData = {
  9. from: "The Subline <clientsupport@thesubline.net>",
  10. to: merchant.email,
  11. subject: "Email verification",
  12. html: VerifyEmail({
  13. name: merchant.name,
  14. link: `${process.env.SITE}/verify/${merchant._id}`,
  15. code: merchant.verifyId
  16. })
  17. }
  18. mailgun.messages().send(mailgunData, (err, body)=>{});
  19. return res.redirect(`/verify/${merchant._id}`);
  20. })
  21. .catch((err)=>{
  22. req.session.error = "ERROR: UNABLE TO SEND VERIFICATION EMAIL";
  23. return res.redirect("/");
  24. });
  25. },
  26. verifyPage: function(req, res){
  27. return res.render("verifyPage/verify", {id: req.params.id});
  28. },
  29. verify: function(req, res){
  30. Merchant.findOne({_id: req.body.id})
  31. .then((merchant)=>{
  32. if(req.body.code !== merchant.verifyId){
  33. req.session.error = "INCORRECT CODE";
  34. return res.redirect(`/verify/${merchant._id}`);
  35. }
  36. merchant.verifyId = undefined;
  37. merchant.status.splice(merchant.status.indexOf("unverified"), 1);
  38. const mailgunList = mailgun.lists("clientsupport@mail.thesubline.com");
  39. const memberData = {
  40. subscribed: true,
  41. address: merchant.email,
  42. name: merchant.name,
  43. vars: {}
  44. }
  45. mailgunList.members().create(memberData, (err, data)=>{});
  46. return merchant.save();
  47. })
  48. .then((merchant)=>{
  49. req.session.user = merchant._id;
  50. return res.redirect("/dashboard");
  51. })
  52. .catch((err)=>{
  53. req.session.error = "ERROR: UNABLE TO VERIFY EMAIL ADDRESS";
  54. return res.redirect("/");
  55. });
  56. }
  57. }