Login.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const md5 = require("md5");
  2. const API = require("../../../lib/API");
  3. const bcryptjs = require('bcryptjs');
  4. const { BaseStdResponse } = require("../../../BaseStdResponse");
  5. const db = require("../../../plugin/DataBase/db");
  6. const Redis = require('../../../plugin/DataBase/Redis');
  7. const sendEmail = require('../../../plugin/Email/Email');
  8. // 用户注册
  9. class Register extends API {
  10. constructor() {
  11. super();
  12. this.setMethod("POST");
  13. this.setPath("/User/Login");
  14. }
  15. createSession(uuid, salt) {
  16. return md5(`${uuid}${salt}${new Date().getTime()}`);
  17. }
  18. async onRequest(req, res) {
  19. let { username, password, text, id } = req.body;
  20. if ([username, password, text, id].some(value => value === '' || value === null || value === undefined)) {
  21. res.json({
  22. ...BaseStdResponse.MISSING_PARAMETER,
  23. endpoint: 1513126
  24. });
  25. return;
  26. }
  27. password = atob(password);
  28. try {
  29. const code = await Redis.get(`captcha:${id}`);
  30. if (!code || code != text)
  31. return res.json({
  32. ...BaseStdResponse.ERR,
  33. msg: '验证码错误或已过期!'
  34. })
  35. } catch (err) {
  36. this.logger.error(`验证图片验证码失败!${err.stack}`);
  37. return res.json({
  38. ...BaseStdResponse.DATABASE_ERR,
  39. msg: '验证失败!'
  40. })
  41. }
  42. let sql = 'SELECT * FROM users WHERE username = ? OR email = ?';
  43. let rows = await db.query(sql, [username, username]);
  44. if (!rows || rows.length !== 1 || !bcryptjs.compareSync(password, rows[0].password))
  45. return res.json({
  46. ...BaseStdResponse.ERR,
  47. msg: '用户名或密码错误'
  48. })
  49. const session = this.createSession(text, Math.random().toFixed(6).slice(-6));
  50. sql = 'UPDATE users SET session = ? WHERE id = ?';
  51. let result = await db.query(sql, [session, rows[0].id]);
  52. if (result && result.affectedRows > 0) {
  53. res.json({
  54. ...BaseStdResponse.OK,
  55. data: {
  56. uuid: rows[0].uuid,
  57. username: rows[0].username,
  58. wxid: rows[0].wxid,
  59. email: rows[0].email,
  60. avatar: rows[0].avatar,
  61. session
  62. }
  63. });
  64. await Redis.del(`captcha:${id}`);
  65. await sendEmail(rows[0].email, '账户登录提醒', `您的Double_X考勤账号${rows[0].username}在${new Date().toLocaleString()}登录了Double_X考勤系统,登录ip:${req.headers['x-forwarded-for'] || req.ip}`);
  66. } else {
  67. res.json({ ...BaseStdResponse.ERR, endpoint: 7894378, msg: '登录失败!' });
  68. }
  69. }
  70. }
  71. module.exports.Register = Register;