const userModel = require('../model/user'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const secret = require('../config/secret'); const Response = require('../util/response'); class UserController { /** * 登录 * @param ctx * @returns {Promise.} */ static async login(ctx) { const data = ctx.request.body; const user = await userModel.findByPhone(data.phone) if (user) { const confirmRes = bcrypt.compareSync(data.password, user.password); if(!confirmRes){ ctx.body = Response.failed('密码错误,请重试') }else{ console.log('ctx',ctx); // ctx.redirect("/"); const token = jwt.sign({ name: user.name, id: user.id }, secret.sign, { expiresIn: '2h' }); ctx.body = Response.success( {user: {phone: user.phone, id: user.id, name: user.name}, token: token}); } } else { ctx.body = Response.failed('此账号不存在'); } } /** * 注册 * @param ctx * @returns {Promise.} */ static async register(ctx) { const data = ctx.request.body; const hashPassword = bcrypt.hashSync(data.password, 10); const user = await userModel.create(data.name, hashPassword, data.phone); if (user) { ctx.body = Response.success({name: user.name}); } else { ctx.body = Response.failed('此手机号已注册'); } } } module.exports = UserController;