| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- 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.<void>}
- */
- 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.<void>}
- */
- 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;
|