'use strict'; const { CrudService } = require('naf-framework-mongoose-free/lib/service'); const { BusinessError, ErrorCode } = require('naf-core').Error; const _ = require('lodash'); const jwt = require('jsonwebtoken'); // 机构 class MechanismService extends CrudService { constructor(ctx) { super(ctx, 'Mechanism'); this.redis = this.app.redis; this.model = this.ctx.model.User.Mechanism; } /** * 创建用户 * @param {Object} params 用户信息 */ async create({ passwd, ...data }) { data.passwd = { secret: passwd }; const { phone } = data; // 检查是否重复 const num = await this.model.count({ phone, isdel: '0' }); if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '已有机构使用该电话号码'); return await this.model.create(data); } /** * 修改密码 * @param {Object} {id,passwd} 用户id和密码 */ async password({ id, passwd }) { const object = await this.model.findById(id); if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息'); object.passwd = { secret: passwd }; await object.save(); } /** * 登陆 * @param {Object} params 登陆信息 * @property phone 手机号 * @property passwd 密码 */ async login({ phone, passwd }) { const object = await this.model.findOne({ phone, isdel: '0' }, '+passwd'); if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息'); const { passwd: op, status } = object; const { secret } = op; if (status !== '1') throw new BusinessError(ErrorCode.ACCESS_DENIED, '拒绝访问!'); if (secret !== passwd) throw new BusinessError(ErrorCode.BAD_passwd, '密码错误'); const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'passwd', '__v' ]); const { secret: secrets } = this.config.jwt; const token = jwt.sign(data, secrets); // 记录登陆 // let number = await this.redis.get('login_number') || 0; // number++; // await this.redis.set('login_number', number); return token; } async delete({ id }) { const object = await this.model.findById(id); if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息'); object.isdel = '1'; await object.save(); } } module.exports = MechanismService;