login.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const jwt = require('jsonwebtoken');
  8. const uuid = require('uuid');
  9. class LoginService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'login');
  12. this.uModel = this.ctx.model.User;
  13. this.stuModel = this.ctx.model.Student;
  14. this.tModel = this.ctx.model.Teacher;
  15. this.schModel = this.ctx.model.School;
  16. this.hModel = this.ctx.model.Headteacher;
  17. }
  18. async login(data) {
  19. const { mobile, passwd } = data;
  20. assert(mobile, 'mobile不能为空');
  21. // assert(/^\d{11}$/i.test(mobile), 'mobile无效');
  22. assert(passwd, 'passwd不能为空');
  23. const res = await this.uModel.findOne({ mobile }, '+passwd');
  24. if (!res) {
  25. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  26. }
  27. // 验证密码
  28. console.log(res.passwd.secret);
  29. console.log(passwd);
  30. if (res.passwd.secret !== passwd) {
  31. throw new BusinessError(ErrorCode.BAD_PASSWORD);
  32. }
  33. return await this.createJwt(res);
  34. }
  35. // 创建登录Token
  36. async createJwt({ _id, name, mobile, openid, type, uid, status }) {
  37. const { secret, expiresIn = '1d', issuer = type } = this.config.jwt;
  38. const subject = mobile;
  39. let _userid = '';
  40. let res = {};
  41. if (type === '0') {
  42. _userid = _id.toString();
  43. res = { userid: _userid, name, type, id: _id, status };
  44. } else if (type === '1') {
  45. _userid = uid.toString();
  46. const result = await this.hModel.findById(_userid);
  47. res = { userid: _userid, name, type, id: _id, status };
  48. } else if (type === '2') {
  49. _userid = uid.toString();
  50. const result = await this.schModel.findById(_userid);
  51. res = { userid: _userid, code: result.code, name, type, id: _id, status };
  52. } else if (type === '3') {
  53. _userid = uid.toString();
  54. const result = await this.tModel.findById(_userid);
  55. res = { userid: _userid, schid: result.schid, schname: result.schname, name, type, id: _id, status };
  56. } else if (type === '4') {
  57. _userid = uid.toString();
  58. const result = await this.stuModel.findById(_userid);
  59. res = { userid: _userid, schid: result.schoolid, schname: result.school_name, termid: result.termid, batchid: result.batchid, classid: result.classid, bedroomid: result.bedroomid, bedroom: result.bedroom, job: result.job, name, type, id: _id, status };
  60. }
  61. const token = await jwt.sign(res, secret, { expiresIn, issuer, subject });
  62. return token;
  63. }
  64. async wxlogin(data) {
  65. const { qrcode, openid } = data;
  66. assert(qrcode, 'qrcode不能为空');
  67. assert(openid, 'openid不能为空');
  68. const key = `naf:qrcode:login:${qrcode}`;
  69. const status = await this.app.redis.get(key);
  70. if (!status) {
  71. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  72. }
  73. if (status !== 'pending') {
  74. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  75. }
  76. const res = await this.uModel.findOne({ openid });
  77. if (!res) {
  78. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  79. }
  80. const result = await this.createJwt(res);
  81. // TODO: 修改二维码状态,登录凭证保存到redis
  82. await this.app.redis.set(key, `scaned:${result}`, 'EX', 600);
  83. // TODO: 发布扫码成功消息
  84. const { mq } = this.ctx;
  85. const ex = 'qrcode.login';
  86. if (mq) {
  87. await mq.topic(ex, qrcode, 'scaned', { durable: true });
  88. }
  89. }
  90. /**
  91. * 创建二维码
  92. * 随机生成二维码,并保存在Redis中,状态初始为pending
  93. * 状态描述:
  94. * pending - 等待扫码
  95. * consumed - 使用二维码登录完成
  96. * ${jwt.token} - Jwt登录凭证
  97. */
  98. async createQrcode() {
  99. const qrcode = uuid();
  100. const key = `naf:qrcode:login:${qrcode}`;
  101. await this.app.redis.set(key, 'pending', 'EX', 600);
  102. return qrcode;
  103. }
  104. // 使用二维码换取登录凭证
  105. async qrcodeLogin(qrcode) {
  106. assert(qrcode, 'qrcode不能为空');
  107. const key = `naf:qrcode:login:${qrcode}`;
  108. const val = await this.app.redis.get(key);
  109. if (!val) {
  110. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  111. }
  112. const [ status, token ] = val.split(':', 2);
  113. if (status !== 'scaned' || !token) {
  114. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码状态无效');
  115. }
  116. // TODO: 修改二维码状态
  117. await this.app.redis.set(key, 'consumed', 'EX', 600);
  118. return { token };
  119. }
  120. // 检查二维码状态
  121. async checkQrcode(qrcode) {
  122. assert(qrcode, 'qrcode不能为空');
  123. const key = `naf:qrcode:login:${qrcode}`;
  124. const val = await this.app.redis.get(key);
  125. if (!val) {
  126. throw new BusinessError(ErrorCode.SERVICE_FAULT, '二维码已过期');
  127. }
  128. const [ status ] = val.split(':', 2);
  129. return { status };
  130. }
  131. }
  132. module.exports = LoginService;