login.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. class LoginService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'login');
  11. this.uModel = this.ctx.model.User;
  12. this.stuModel = this.ctx.model.Student;
  13. this.tModel = this.ctx.model.Teacher;
  14. this.schModel = this.ctx.model.School;
  15. this.hModel = this.ctx.model.Headteacher;
  16. }
  17. async login(data) {
  18. const { mobile, passwd } = data;
  19. assert(mobile, 'mobile不能为空');
  20. // assert(/^\d{11}$/i.test(mobile), 'mobile无效');
  21. assert(passwd, 'passwd不能为空');
  22. const res = await this.uModel.findOne({ mobile }, '+passwd');
  23. if (!res) {
  24. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  25. }
  26. // 验证密码
  27. console.log(res.passwd.secret);
  28. console.log(passwd);
  29. if (res.passwd.secret !== passwd) {
  30. throw new BusinessError(ErrorCode.BAD_PASSWORD);
  31. }
  32. return await this.createJwt(res);
  33. }
  34. // 创建登录Token
  35. async createJwt({ _id, name, mobile, openid, type, uid }) {
  36. const { secret, expiresIn = '1d', issuer = type } = this.config.jwt;
  37. const subject = mobile;
  38. let _userid = '';
  39. let res = {};
  40. if (type === '0') {
  41. _userid = _id.toString();
  42. } else if (type === '1') {
  43. _userid = uid.toString();
  44. res = await this.hModel.findById(_userid);
  45. } else if (type === '2') {
  46. _userid = uid.toString();
  47. res = await this.schModel.findById(_userid);
  48. } else if (type === '3') {
  49. _userid = uid.toString();
  50. res = await this.tModel.findById(_userid);
  51. } else if (type === '4') {
  52. _userid = uid.toString();
  53. res = await this.stuModel.findById(_userid);
  54. }
  55. res.userid = _userid;
  56. res.openid = openid;
  57. res.type = type;
  58. const token = await jwt.sign(...res, secret, { expiresIn, issuer, subject });
  59. return token;
  60. }
  61. async wxlogin(data) {
  62. const { openid } = data;
  63. assert(openid, 'openid不能为空');
  64. const res = await this.uModel.findOne({ openid });
  65. let newdata = {};
  66. if (!res) {
  67. throw new BusinessError(ErrorCode.USER_NOT_EXIST);
  68. } else {
  69. newdata = { id: res.id, name: res.name, openid: res.openid, type: res.type };
  70. }
  71. return await newdata;
  72. }
  73. }
  74. module.exports = LoginService;