| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- const db = require('../../db/index.js');
- const bcrypt = require("bcryptjs");
- const jwt = require("jsonwebtoken");
- const config = require('../../config.js')
- //用户注册
- exports.regUser = (req, res) => {
- const userInfo = req.body
- // if (!userInfo.username || !userInfo.password) {
- // // return res.send({
- // // status: 200,
- // // message: "用户名或密码不能为空!"
- // // })
- // return res.rescc("用户名或密码不能为空!");
- // }
- const sqlStr = "select * from ev_users where username=?"
- db.query(sqlStr, userInfo.username, (err, results) => {
- if (err) {
- // return res.send({
- // status: 500,
- // message: err.message
- // })
- return res.rescc(err);
- }
- if (results.length > 0) {
- // return res.send({
- // status: 200,
- // message: "用户名已被占用,请更换用户名!"
- // })
- return res.rescc("用户名已被占用,请更换用户名!");
- }
- //对密码进行加密
- userInfo.password = bcrypt.hashSync(userInfo.password, 10);
- const sql = "insert into ev_users set ?"
- db.query(sql, { username: userInfo.username, password: userInfo.password }, (err, results) => {
- if (err) {
- // return res.send({status: 500, message: err.message})
- return res.rescc(err);
- }
- if (results.affectedRows !== 1) {
- // return res.send({ status: 500, message: "注册失败,请稍后再试!" })
- return res.rescc("注册失败,请稍后再试!");
- }
- // res.send({status: 200, message: "注册成功"})
- res.rescc("注册成功", 200);
- })
- })
- }
- //用户登录
- exports.login = (req, res) => {
- const userInfo = req.body
- const sql = "select * from ev_users where username=?"
- db.query(sql, userInfo.username, (err, results) => {
- if (err) {
- return res.rescc(err);
- }
- if (results.length !== 1) {
- return res.rescc("登录失败");
- }
- //校验密码
- const compareResult = bcrypt.compareSync(userInfo.password, results[0].password);
- if (!compareResult) {
- return res.rescc("密码不正确,登录失败");
- }
- //生产JWT token字符串
- const user = { ...results[0], password: '', user_pic: '' };
- //对用户信息加密
- const tokenStr = jwt.sign(user, config.jwtSecretKey, {
- expiresIn: "10h"
- })
- const data = {
- status: 200,
- message: "登录成功",
- token: tokenStr
- }
- res.rescc("", 200, data);
- })
- }
|