|
@@ -0,0 +1,59 @@
|
|
|
+'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;
|
|
|
+ }
|
|
|
+
|
|
|
+ async login(data) {
|
|
|
+ const { mobile, passwd } = data;
|
|
|
+ assert(mobile, 'mobile不能为空');
|
|
|
+ assert(/^\d{11}$/i.test(mobile), 'mobile无效');
|
|
|
+ assert(passwd, 'passwd不能为空');
|
|
|
+ let 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 }) {
|
|
|
+ const { secret, expiresIn = '1d' } = this.config.jwt;
|
|
|
+ const subject = mobile;
|
|
|
+ const token = await jwt.sign({ userid: _id.toString(), name, openid }, secret, { expiresIn, issuer, subject });
|
|
|
+ return token;
|
|
|
+ }
|
|
|
+
|
|
|
+ async wxlogin(data) {
|
|
|
+ const { openid } = data;
|
|
|
+ assert(openid, 'openid不能为空');
|
|
|
+ let res = await this.uModel.findOne({ openid });
|
|
|
+ let newdata = {};
|
|
|
+ if (!res) {
|
|
|
+ res = await this.uModel.findOne({ openid });
|
|
|
+ if (!res) {
|
|
|
+ throw new BusinessError(ErrorCode.USER_NOT_EXIST);
|
|
|
+ }
|
|
|
+ newdata = { id: res.id, name: res.name, openid: res.openid, type: 'patient' };
|
|
|
+ } else {
|
|
|
+ newdata = { id: res.id, name: res.name, openid: res.openid, type: 'doctor' };
|
|
|
+ }
|
|
|
+ return await newdata;
|
|
|
+ }
|
|
|
+}
|
|
|
+module.exports = LoginService;
|