'use strict'; const Service = require('egg').Service; const assert = require('assert'); const moment = require('moment'); const crypto = require('crypto'); class adminUserService extends Service { async create({ acct, password, userName, phone, state, roleList }) { assert(acct, '帐号不存在'); assert(password, '密码不存在'); assert(userName, '用户名不存在'); assert(state, '状态不存在'); const { AdminUser: model } = this.ctx.model; const user = await model.find({ acct }); if (user.length > 0) return { errmsg: '帐号已存在', errcode: -2001 }; const createAt = moment().format('x'); const hash = crypto.createHmac('sha256', this.app.config.userSecret); const pwa = hash.update(password).digest('hex'); try { const res = await model.create({ acct, password: pwa, userName, phone, createAt, state, roleList }); return { errmsg: '', errcode: 0, res }; } catch (error) { console.log(error); throw new Error('添加失败'); } } async update({ userName, phone, _id, roleList, state, password }) { assert(_id, 'id不存在'); const { AdminUser: model } = this.ctx.model; try { const hash = crypto.createHmac('sha256', this.app.config.userSecret); const pwd = hash.update(password).digest('hex'); await model.findById(_id).update({ userName, phone, roleList, state, password: pwd }); return { errmsg: '', errcode: 0 }; } catch (error) { console.log(error); throw new Error('修改失败'); } } async pwdUpdate({ password, userName, confirmPwd }) { console.log(password, userName, confirmPwd); assert(userName, '用户名不存在'); const { AdminUser: model } = this.ctx.model; const hash = crypto.createHmac('sha256', this.app.config.userSecret); const cpwd = hash.update(confirmPwd).digest('hex'); try { const res = await model.findOne({ userName }); if (res.password !== cpwd) { return { errmsg: '原密码错误', errcode: -2003 }; } const hash = crypto.createHmac('sha256', this.app.config.userSecret); const pwd = hash.update(password).digest('hex'); await model.findByIdAndUpdate(res._id, { password: pwd }); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error('修改失败'); } } async del({ id }) { assert(id, 'id不存在'); const { AdminUser: model } = this.ctx.model; try { await model.findById(id).remove(); return { errmsg: '', errcode: 0 }; } catch (error) { throw new Error('删除失败'); } } async query({ skip, limit, userName, state, acct }) { const { AdminUser: model } = this.ctx.model; const filter = {}; if (userName) filter.userName = userName; if (state) filter.state = state; if (acct) filter.acct = acct; try { let res; const total = await model.find({ ...filter }); if (skip && limit) { res = await model.find({ ...filter }, { password: false }).skip(Number(skip) * Number(limit)).limit(Number(limit)); } else { res = await model.find({ ...filter }, { password: false }); } return { errmsg: '', errcode: 0, data: res, total: total.length }; } catch (error) { throw new Error('查询失败'); } } } module.exports = adminUserService;