ChangePassword.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. try {
  22. let { uuid, session, oldpassword, password } = req.body;
  23. if ([uuid, session, 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.status(401).json({
  32. ...BaseStdResponse.ACCESS_DENIED,
  33. endpoint: 48153145
  34. });
  35. }
  36. password = atob(password);
  37. if (!this.CheckPassword(password))
  38. return res.json({
  39. ...BaseStdResponse.ERR,
  40. msg: '密码需在8到16位之间,且包含字母和数字'
  41. })
  42. if (oldpassword && oldpassword !== '') {
  43. oldpassword = atob(oldpassword);
  44. let sql = 'SELECT email, password FROM users WHERE uuid = ? AND password IS NULL';
  45. let rows = await db.query(sql, [uuid]);
  46. if (!rows || rows.length === 0)
  47. return res.json({
  48. ...BaseStdResponse.ERR,
  49. msg: '暂时无法重设密码,请联系客服'
  50. })
  51. if (oldpassword !== '' && !bcryptjs.compareSync(oldpassword, rows[0].password))
  52. return res.json({
  53. ...BaseStdResponse.ERR,
  54. msg: '密码错误!'
  55. })
  56. }
  57. const hashPassword = bcryptjs.hashSync(password, 10);
  58. let sql = 'UPDATE users SET password = ? WHERE uuid = ?';
  59. let result = await db.query(sql, [hashPassword, uuid]);
  60. if (result && result.affectedRows > 0) {
  61. res.json({
  62. ...BaseStdResponse.OK
  63. });
  64. } else {
  65. res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '操作失败!' });
  66. }
  67. } catch (error) {
  68. return res.json({
  69. ...BaseStdResponse.ERR,
  70. msg: '密码更新失败,请联系客服'
  71. })
  72. }
  73. }
  74. }
  75. module.exports.ChangePassword = ChangePassword;