1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose-free/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- const { ObjectId } = require('mongoose').Types;
- // 用户相关
- class UserService extends CrudService {
- constructor(ctx) {
- super(ctx, 'user');
- this.model = this.ctx.model.User;
- }
- /**
- * 创建用户
- * @param {Object} params 用户信息
- */
- async create({ password, ...data }) {
- data.password = { secret: password };
- const { phone } = data;
- // 检查手机号
- const num = await this.model.count({ phone });
- if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '已有人员 使用该手机号');
- const res = await this.model.create(data);
- return res;
- }
- /**
- * 修改密码
- * @param {Object} {id,password} 用户id和密码
- */
- async password({ id, password }) {
- const object = await this.model.findById(id);
- if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
- object.password = { secret: password };
- await object.save();
- }
- /**
- * 管理员登陆
- * @param {Object} params 登陆信息
- * @property phone 电话号
- * @property password 密码
- */
- async login({ phone, password, openid }) {
- let object;
- if (!openid) object = await this.model.findOne({ phone }, '+password');
- else object = await this.model.findOne({ openid });
- if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
- if (!openid) {
- const { password: op } = object;
- const { secret } = op;
- if (secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
- }
- const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'password', '__v' ]);
- return data;
- }
- }
- module.exports = UserService;
|