12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const { ObjectId } = require('mongoose').Types;
- const _ = require('lodash');
- const jwt = require('jsonwebtoken');
- // 管理员
- class AdminService extends CrudService {
- constructor(ctx) {
- super(ctx, 'admin');
- this.model = this.ctx.model.Admin;
- }
- /**
- * 创建用户
- * @param {Object} params 用户信息
- */
- async create({ passwd, ...data }) {
- data.passwd = { secret: passwd };
- 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,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 code_phone code或者是phone
- * @property passwd 密码
- */
- async login({ code_phone, passwd }) {
- const object = await this.model.findOne({ $or: [{ code: code_phone }, { phone: code_phone }] }, '+passwd');
- if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息');
- const { passwd: op } = object;
- const { secret } = op;
- if (secret !== passwd) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
- const data = _.omit(JSON.parse(JSON.stringify(object)), [ 'meta', 'passwd', '__v' ]);
- const { secret: secrets } = this.config.jwt;
- const token = jwt.sign(data, secrets);
- return token;
- }
- }
- module.exports = AdminService;
|