SendEmail.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. default:
  45. return res.json({
  46. ...BaseStdResponse.METHOD_NOT_EXIST
  47. })
  48. }
  49. const code = Math.random().toFixed(6).slice(-6);
  50. try {
  51. await Redis.set(`email:${email}`, code, {
  52. EX: 600
  53. });
  54. await sendEmail(email, '验证码', `${content}您的验证码为:${code}。此验证码10分钟内有效,请妥善保管您的验证码,非本人操作请忽略。`);
  55. } catch (err) {
  56. this.logger.error(`发送邮箱验证码失败!${err.stack}`);
  57. return res.json({
  58. ...BaseStdResponse.SMS_SEND_FAIL,
  59. msg: '请检查邮箱格式后再试!'
  60. })
  61. }
  62. res.json({
  63. ...BaseStdResponse.OK
  64. })
  65. }
  66. }
  67. module.exports.SendEmail = SendEmail;