ChangePassword.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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, oldpassword, 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. oldpassword = atob(oldpassword);
  36. password = atob(password);
  37. if (!this.CheckPassword(password))
  38. return res.json({
  39. ...BaseStdResponse.ERR,
  40. msg: '密码需在8到16位之间,且包含字母和数字'
  41. })
  42. let sql = 'SELECT email, password FROM users WHERE uuid = ?';
  43. let rows = await db.query(sql, [uuid]);
  44. if(!rows || rows.length === 0)
  45. return res.json({
  46. ...BaseStdResponse.DATABASE_ERR
  47. })
  48. if (!bcryptjs.compareSync(oldpassword, rows[0].password))
  49. return res.json({
  50. ...BaseStdResponse.ERR,
  51. msg: '密码错误!'
  52. })
  53. const hashPassword = bcryptjs.hashSync(password, 10);
  54. sql = 'UPDATE users SET password = ? WHERE uuid = ?';
  55. let result = await db.query(sql, [hashPassword, uuid]);
  56. if (result && result.affectedRows > 0) {
  57. res.json({
  58. ...BaseStdResponse.OK
  59. });
  60. } else {
  61. res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '操作失败!' });
  62. }
  63. }
  64. }
  65. module.exports.ChangePassword = ChangePassword;