user.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. console.log('ctx.cookies.redirect_uri',ctx.cookies.get('redirect_uri'));
  22. let redirect_uri = ctx.cookies.get('redirect_uri');
  23. let data = {
  24. iss : 'http://'+ process.env.HOST,
  25. sub: encodeURIComponent("uid=" + user.id + "&name=" + uid.name + "&phone=" + user.phone),
  26. aud: ctx.cookies.get('client_id'),
  27. auth_time: new Date().getTime() / 1000,
  28. iat: new Date().getTime() / 1000,
  29. exp: new Date().getTime() / 1000 + 24 * 60 * 60,
  30. };
  31. const token = jwt.sign(data, secret.sign);
  32. ctx.set('Content-Type', 'application/x-www-form-urlencoded');
  33. ctx.redirect(redirect_uri + "?id_token=" + token);
  34. // ctx.body = Response.success(
  35. // {user: {phone: user.phone, id: user.id, name: user.name},
  36. // token: token});
  37. }
  38. } else {
  39. ctx.body = Response.failed('此账号不存在');
  40. }
  41. }
  42. /**
  43. * 注册
  44. * @param ctx
  45. * @returns {Promise.<void>}
  46. */
  47. static async register(ctx) {
  48. const data = ctx.request.body;
  49. const hashPassword = bcrypt.hashSync(data.password, 10);
  50. const user = await userModel.create(data.name, hashPassword, data.phone);
  51. if (user) {
  52. ctx.body = Response.success({name: user.name});
  53. } else {
  54. ctx.body = Response.failed('此手机号已注册');
  55. }
  56. }
  57. }
  58. module.exports = UserController;