user.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const db = require('../../db/index.js');
  2. const bcrypt = require("bcryptjs");
  3. const jwt = require("jsonwebtoken");
  4. const config = require('../../config.js')
  5. //用户注册
  6. exports.regUser = (req, res) => {
  7. const userInfo = req.body
  8. // if (!userInfo.username || !userInfo.password) {
  9. // // return res.send({
  10. // // status: 200,
  11. // // message: "用户名或密码不能为空!"
  12. // // })
  13. // return res.rescc("用户名或密码不能为空!");
  14. // }
  15. const sqlStr = "select * from ev_users where username=?"
  16. db.query(sqlStr, userInfo.username, (err, results) => {
  17. if (err) {
  18. // return res.send({
  19. // status: 500,
  20. // message: err.message
  21. // })
  22. return res.rescc(err);
  23. }
  24. if (results.length > 0) {
  25. // return res.send({
  26. // status: 200,
  27. // message: "用户名已被占用,请更换用户名!"
  28. // })
  29. return res.rescc("用户名已被占用,请更换用户名!");
  30. }
  31. //对密码进行加密
  32. userInfo.password = bcrypt.hashSync(userInfo.password, 10);
  33. const sql = "insert into ev_users set ?"
  34. db.query(sql, { username: userInfo.username, password: userInfo.password }, (err, results) => {
  35. if (err) {
  36. // return res.send({status: 500, message: err.message})
  37. return res.rescc(err);
  38. }
  39. if (results.affectedRows !== 1) {
  40. // return res.send({ status: 500, message: "注册失败,请稍后再试!" })
  41. return res.rescc("注册失败,请稍后再试!");
  42. }
  43. // res.send({status: 200, message: "注册成功"})
  44. res.rescc("注册成功", 200);
  45. })
  46. })
  47. }
  48. //用户登录
  49. exports.login = (req, res) => {
  50. const userInfo = req.body
  51. const sql = "select * from ev_users where username=?"
  52. db.query(sql, userInfo.username, (err, results) => {
  53. if (err) {
  54. return res.rescc(err);
  55. }
  56. if (results.length !== 1) {
  57. return res.rescc("登录失败");
  58. }
  59. //校验密码
  60. const compareResult = bcrypt.compareSync(userInfo.password, results[0].password);
  61. if (!compareResult) {
  62. return res.rescc("密码不正确,登录失败");
  63. }
  64. //生产JWT token字符串
  65. const user = { ...results[0], password: '', user_pic: '' };
  66. //对用户信息加密
  67. const tokenStr = jwt.sign(user, config.jwtSecretKey, {
  68. expiresIn: "10h"
  69. })
  70. const data = {
  71. status: 200,
  72. message: "登录成功",
  73. token: tokenStr
  74. }
  75. res.rescc("", 200, data);
  76. })
  77. }