'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(); } else if (type === '1') { _userid = uid.toString(); res = await this.hModel.findById(_userid); } else if (type === '2') { _userid = uid.toString(); res = await this.schModel.findById(_userid); } else if (type === '3') { _userid = uid.toString(); res = await this.tModel.findById(_userid); } else if (type === '4') { _userid = uid.toString(); res = await this.stuModel.findById(_userid); } const newdata = { userid: _userid, ...res, openid, type }; const token = await jwt.sign(newdata, 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;