123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- 'use strict';
- const assert = require('assert');
- const _ = require('lodash');
- const { ObjectId } = require('mongoose').Types;
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const jwt = require('jsonwebtoken');
- class LoginService extends CrudService {
- constructor(ctx) {
- super(ctx, 'login');
- this.uModel = this.ctx.model.User;
- this.stuModel = this.ctx.model.Student;
- this.tModel = this.ctx.model.Teacher;
- this.schModel = this.ctx.model.School;
- this.hModel = this.ctx.model.Headteacher;
- }
- async login(data) {
- const { mobile, passwd } = data;
- assert(mobile, 'mobile不能为空');
- // assert(/^\d{11}$/i.test(mobile), 'mobile无效');
- assert(passwd, 'passwd不能为空');
- const res = await this.uModel.findOne({ mobile }, '+passwd');
- if (!res) {
- throw new BusinessError(ErrorCode.USER_NOT_EXIST);
- }
- // 验证密码
- console.log(res.passwd.secret);
- console.log(passwd);
- if (res.passwd.secret !== passwd) {
- throw new BusinessError(ErrorCode.BAD_PASSWORD);
- }
- return await this.createJwt(res);
- }
- // 创建登录Token
- async createJwt({ _id, name, mobile, openid, type, uid }) {
- const { secret, expiresIn = '1d', issuer = type } = this.config.jwt;
- const subject = mobile;
- let _userid = '';
- let res = {};
- if (type === '0') {
- _userid = _id.toString();
- res = { userid: _userid, name, type, id: _id };
- } else if (type === '1') {
- _userid = uid.toString();
- const result = await this.hModel.findById(_userid);
- res = { userid: _userid, name, type, id: _id };
- } else if (type === '2') {
- _userid = uid.toString();
- const result = await this.schModel.findById(_userid);
- res = { userid: _userid, code: result.code, name, type, id: _id };
- } else if (type === '3') {
- _userid = uid.toString();
- const result = await this.tModel.findById(_userid);
- res = { userid: _userid, schid: result.schid, schname: result.schname, name, type, id: _id };
- } else if (type === '4') {
- _userid = uid.toString();
- const result = await this.stuModel.findById(_userid);
- res = { userid: _userid, schid: result.schoolid, schname: result.school_name, name, type, id: _id };
- }
- const token = await jwt.sign(res, secret, { expiresIn, issuer, subject });
- return token;
- }
- async wxlogin(data) {
- const { openid } = data;
- assert(openid, 'openid不能为空');
- const res = await this.uModel.findOne({ openid });
- let newdata = {};
- if (!res) {
- throw new BusinessError(ErrorCode.USER_NOT_EXIST);
- } else {
- newdata = { id: res.id, name: res.name, openid: res.openid, type: res.type };
- }
- return await newdata;
- }
- }
- module.exports = LoginService;
|