ChangePassword.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. const API = require("../../../lib/API");
  2. const db = require("../../../plugin/DataBase/db");
  3. const { BaseStdResponse } = require("../../../BaseStdResponse");
  4. const sendEmail = require('../../../plugin/Email/Email');
  5. const AccessControl = require("../../../lib/AccessControl");
  6. const bcryptjs = require('bcryptjs');
  7. class ChangePassword extends API {
  8. constructor() {
  9. super();
  10. this.setMethod("POST");
  11. this.setPath("/User/ChangePassword");
  12. }
  13. CheckPassword(password) {
  14. if (password.length < 8 || password.length > 16) {
  15. return false;
  16. }
  17. const hasLetter = /[a-zA-Z]/.test(password);
  18. const hasNumber = /\d/.test(password);
  19. return hasLetter && hasNumber;
  20. }
  21. async onRequest(req, res) {
  22. let { uuid, session, oldpassword, password } = req.body;
  23. if ([uuid, session, oldpassword, password].some(value => value === '' || value === null || value === undefined)) {
  24. return res.json({
  25. ...BaseStdResponse.MISSING_PARAMETER,
  26. endpoint: 1513126
  27. });
  28. }
  29. // 检查 session 是否有效
  30. if (!await AccessControl.checkSession(uuid, session)) {
  31. return res.json({
  32. ...BaseStdResponse.ACCESS_DENIED,
  33. endpoint: 48153145
  34. });
  35. }
  36. oldpassword = atob(oldpassword);
  37. password = atob(password);
  38. if (!this.CheckPassword(password))
  39. return res.json({
  40. ...BaseStdResponse.ERR,
  41. msg: '密码需在8到16位之间,且包含字母和数字'
  42. })
  43. let sql = 'SELECT email, password FROM users WHERE uuid = ?';
  44. let rows = await db.query(sql, [uuid]);
  45. if(!rows || rows.length === 0)
  46. return res.json({
  47. ...BaseStdResponse.DATABASE_ERR
  48. })
  49. if (!bcryptjs.compareSync(oldpassword, rows[0].password))
  50. return res.json({
  51. ...BaseStdResponse.ERR,
  52. msg: '密码错误!'
  53. })
  54. const hashPassword = bcryptjs.hashSync(password, 10);
  55. sql = 'UPDATE users SET password = ? WHERE uuid = ?';
  56. let result = await db.query(sql, [hashPassword, uuid]);
  57. if (result && result.affectedRows > 0) {
  58. res.json({
  59. ...BaseStdResponse.OK
  60. });
  61. await sendEmail(rows[0].email, '更改成功', `您的Double_X考勤账号更改密码成功,操作时间:${new Date().toLocaleString()}`);
  62. } else {
  63. res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '操作失败!' });
  64. }
  65. }
  66. }
  67. module.exports.ChangePassword = ChangePassword;