'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 UserService extends CrudService { constructor(ctx) { super(ctx, 'user'); this.model = this.ctx.model.User; this.rmodel = this.ctx.model.Role; } // 重写创建方法 async create(data) { const { name, mobile, passwd } = data; console.log(data); assert(name && mobile && passwd, '缺少部分信息项'); assert(/^\d{11}$/i.test(mobile), 'mobile无效'); const user = await this.model.findOne({ mobile }); if (user) { throw new BusinessError(ErrorCode.DATA_EXISTED); } const newdata = data; const pas = await this.createJwtPwd(passwd); newdata.passwd = { secret: pas }; const res = await this.model.create(newdata); return res; } // 创建登录Token async createJwtPwd(password) { const { secret, expiresIn, issuer } = this.config.jwt; const token = await jwt.sign(password, secret); return token; } // 重写修改方法 async update({ id }, data) { const { name, mobile, passwd, openid, roles, remark, uid } = data; const user = await this.model.findById(id, '+passwd'); if (name) { user.name = name; } if (mobile) { user.mobile = mobile; } if (passwd) { const newpasswd = await this.createJwtPwd(passwd); user.passwd = { secret: newpasswd }; } if (openid) { user.openid = openid; } if (roles) { user.roles = roles; } if (uid) { user.uid = uid; } if (remark) { user.remark = remark; } await user.save(); } // 用户修改密码 async uppasswd(data) { const { id, oldpasswd, newpasswd } = data; assert(id && oldpasswd && newpasswd, '缺少部分信息项'); // 根据用户id查询其他用户表中是否存在相应数据 const user = await this.model.findById(id, '+passwd'); // 如果用户不存在抛出异常 if (!user) { throw new BusinessError(ErrorCode.USER_NOT_EXIST); } // 将用户输入的密码进行加密并与查询到的用户数据密码相比对 const _oldpasswd = await this.createJwtPwd(oldpasswd); // 如果两个密码不一致抛出异常 if (_oldpasswd !== user.passwd.secret) { throw new BusinessError(ErrorCode.BAD_PASSWORD); } const _newpasswd = await this.createJwtPwd(newpasswd); user.passwd = { secret: _newpasswd }; await user.save(); } } module.exports = UserService;