ChangePassword.js 2.6 KB

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