ForgetPassword.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. const md5 = require("md5");
  2. const API = require("../../../lib/API");
  3. const bcryptjs = require('bcryptjs');
  4. const db = require("../../../plugin/DataBase/db");
  5. const { BaseStdResponse } = require("../../../BaseStdResponse");
  6. const Redis = require('../../../plugin/DataBase/Redis');
  7. const sendEmail = require('../../../plugin/Email/Email');
  8. // 找回密码
  9. class ForgetPassword extends API {
  10. constructor() {
  11. super();
  12. this.setMethod("POST");
  13. this.setPath("/User/ForgetPassword");
  14. }
  15. CheckPassword(password) {
  16. if (password.length < 8 || password.length > 16) {
  17. return false;
  18. }
  19. const hasLetter = /[a-zA-Z]/.test(password);
  20. const hasNumber = /\d/.test(password);
  21. return hasLetter && hasNumber;
  22. }
  23. createSession(uuid, salt) {
  24. return md5(`${uuid}${salt}${new Date().getTime()}`);
  25. }
  26. async onRequest(req, res) {
  27. let { username, email, code, password } = req.body;
  28. if ([username, email, code, password].some(value => value === '' || value === null || value === undefined)) {
  29. res.json({
  30. ...BaseStdResponse.MISSING_PARAMETER,
  31. endpoint: 1513126
  32. });
  33. return;
  34. }
  35. if (!this.CheckPassword(password))
  36. return res.json({
  37. ...BaseStdResponse.ERR,
  38. msg: '密码需在8到16位之间,且包含字母和数字'
  39. })
  40. let sql = 'SELECT id FROM users WHERE username = ? AND email = ?';
  41. let Rows = await db.query(sql, [username, email]);
  42. if (Rows.length === 0)
  43. return res.json({
  44. ...BaseStdResponse.USER_NOT_EXISTS,
  45. msg: '用户名和邮箱不匹配!'
  46. })
  47. password = atob(password);
  48. try {
  49. const VerifyCode = await Redis.get(`email:${email}`);
  50. if (!VerifyCode || VerifyCode != code)
  51. return res.json({
  52. ...BaseStdResponse.SMS_CHECK_FAIL,
  53. msg: '邮箱验证码输入错误或已过期'
  54. })
  55. } catch (err) {
  56. this.logger.error(`验证邮箱验证码失败!${err.stack}`);
  57. return res.json({
  58. ...BaseStdResponse.DATABASE_ERR,
  59. msg: '验证失败!'
  60. })
  61. }
  62. const session = this.createSession(code, Math.random().toFixed(6).slice(-6));
  63. const hashPassword = bcryptjs.hashSync(password, 10);
  64. sql = 'UPDATE users SET password = ? , session = ? WHERE id = ?';
  65. let result = await db.query(sql, [hashPassword, session, Rows[0].id]);
  66. if (result && result.affectedRows > 0) {
  67. await Redis.del(`email:${email}`);
  68. res.json({
  69. ...BaseStdResponse.OK
  70. });
  71. await sendEmail(email, '密码修改提醒', `您已成功修改Double_X考勤账号密码,用户名${username},修改时间:${new Date().toLocaleString()}`);
  72. } else {
  73. res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '修改失败!'});
  74. }
  75. }
  76. }
  77. module.exports.ForgetPassword = ForgetPassword;