'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 assert = require('assert'); const jwt = require('jsonwebtoken'); // 管理员 class UserService extends CrudService { constructor(ctx) { super(ctx, 'user'); this.model = this.ctx.model.User; } async init() { const count = await this.model.count({ login_id: 'admin' }); if (count <= 0) { const data = { name: '管理员', login_id: 'admin', password: { secret: '123456' }, }; await this.model.create(data); } } /** * 管理员登陆 * @param {Object} params 登陆信息 * @property login_id code或者是phone * @property password 密码 */ async login({ login_id, password }) { const object = await this.model.findOne({ login_id }, '+password'); if (!object) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到用户的信息'); 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' ]); const { secret: secrets } = this.config.jwt; const token = jwt.sign(data, secrets); return token; } } module.exports = UserService;