user.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const userModel = require('../model/user');
  2. const jwt = require('jsonwebtoken');
  3. const bcrypt = require('bcrypt');
  4. const secret = require('../config/secret');
  5. const Response = require('../util/response');
  6. class UserController {
  7. /**
  8. * 登录
  9. * @param ctx
  10. * @returns {Promise.<void>}
  11. */
  12. static async login(ctx) {
  13. const data = ctx.request.body;
  14. const user = await userModel.findByPhone(data.phone)
  15. if (user) {
  16. const confirmRes = bcrypt.compareSync(data.password, user.password);
  17. if(!confirmRes){
  18. ctx.body = Response.failed('密码错误,请重试')
  19. }else{
  20. console.log('ctx',ctx);
  21. // ctx.redirect("/");
  22. const token = jwt.sign({
  23. name: user.name,
  24. id: user.id
  25. }, secret.sign, { expiresIn: '2h' });
  26. ctx.body = Response.success(
  27. {user: {phone: user.phone, id: user.id, name: user.name},
  28. token: token});
  29. }
  30. } else {
  31. ctx.body = Response.failed('此账号不存在');
  32. }
  33. }
  34. /**
  35. * 注册
  36. * @param ctx
  37. * @returns {Promise.<void>}
  38. */
  39. static async register(ctx) {
  40. const data = ctx.request.body;
  41. const hashPassword = bcrypt.hashSync(data.password, 10);
  42. const user = await userModel.create(data.name, hashPassword, data.phone);
  43. if (user) {
  44. ctx.body = Response.success({name: user.name});
  45. } else {
  46. ctx.body = Response.failed('此手机号已注册');
  47. }
  48. }
  49. }
  50. module.exports = UserController;