SendEmail.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const API = require("../../../lib/API");
  2. const { BaseStdResponse } = require("../../../BaseStdResponse");
  3. const Redis = require('../../../plugin/DataBase/Redis');
  4. const sendEmail = require('../../../plugin/Email/Email');
  5. // 发送邮箱验证码
  6. class SendEmail extends API {
  7. constructor() {
  8. super();
  9. this.setMethod("POST");
  10. this.setPath("/User/SendEmail");
  11. }
  12. async onRequest(req, res) {
  13. const { email, text, id, type } = req.body;
  14. if ([email, text, id, type].some(value => value === '' || value === null || value === undefined)) {
  15. res.json({
  16. ...BaseStdResponse.MISSING_PARAMETER,
  17. endpoint: 1513126
  18. });
  19. return;
  20. }
  21. try {
  22. const code = await Redis.get(`captcha:${id}`);
  23. if (!code || code != text)
  24. return res.json({
  25. ...BaseStdResponse.SMS_CHECK_FAIL,
  26. msg: '验证码输入错误或已过期'
  27. })
  28. await Redis.del(`captcha:${id}`);
  29. } catch (err) {
  30. this.logger.error(`验证图片验证码失败!${err.stack}`);
  31. return res.json({
  32. ...BaseStdResponse.DATABASE_ERR,
  33. msg: '验证失败!'
  34. })
  35. }
  36. let content;
  37. switch (type) {
  38. case 'register':
  39. content = '您正在注册Double_X考勤系统账号,';
  40. break;
  41. case 'forget':
  42. content = '您正在找回Double_X考勤系统账号,';
  43. break;
  44. case 'bind':
  45. content = '您正在进行换绑邮箱操作,';
  46. break;
  47. default:
  48. return res.json({
  49. ...BaseStdResponse.METHOD_NOT_EXIST
  50. })
  51. }
  52. const code = Math.random().toFixed(6).slice(-6);
  53. try {
  54. await Redis.set(`email:${email}`, code, {
  55. EX: 600
  56. });
  57. await sendEmail(email, '验证码', `${content}您的验证码为:${code}。此验证码10分钟内有效,请妥善保管您的验证码,非本人操作请忽略。`);
  58. } catch (err) {
  59. this.logger.error(`发送邮箱验证码失败!${err.stack}`);
  60. return res.json({
  61. ...BaseStdResponse.SMS_SEND_FAIL,
  62. msg: '请检查邮箱格式后再试!'
  63. })
  64. }
  65. res.json({
  66. ...BaseStdResponse.OK
  67. })
  68. }
  69. }
  70. module.exports.SendEmail = SendEmail;