'use strict'; const Service = require('egg').Service; const assert = require('assert'); const menu = require('../public/adminMenu'); const svgCaptcha = require('svg-captcha'); const sm3 = require('sm3'); class UserService extends Service { async login({ acct, password, code }) { assert(acct, '帐号不存在'); assert(password, '密码不存在'); assert(code, '验证码不存在'); const captcha = this.ctx.session.code; if (captcha !== code) { return { errmsg: '验证码错误', errcode: -2003 }; } const { AdminUser: model } = this.ctx.model; try { const res = await model.findOne({ acct }); if (!res) { return { errmsg: '用户不存在', errcode: -2003 }; } const userInfo = res; if (userInfo.state !== '0') { return { errmsg: '用户状态异常', errcode: -2003 }; } const pwd = sm3(`${password}:${userInfo.salt}`); if (userInfo.password !== pwd) { return { errmsg: '密码错误', errcode: -2003 }; } const token = this.app.jwt.sign({ acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id }, this.app.config.jwt.secret); return { errmsg: '', errcode: 0, token, userInfo: { acct: userInfo.acct, userName: userInfo.userName, id: userInfo._id } }; } catch (error) { throw new Error('登录失败'); } } async getUserMenu() { const { AdminUser: model } = this.ctx.model; const { Role: rolemodel } = this.ctx.model; try { const str = this.ctx.request.header.authorization; const token = str.substring(7); const decode = this.ctx.app.jwt.verify(token, this.app.config.jwt.secret); const menulist = []; const res = await model.find({ acct: decode.acct }); if (res.length > 0) { const userRoleList = res[0].roleList; if (userRoleList && userRoleList.length > 0) { for (let e = 0; e < userRoleList.length; e++) { const role = await rolemodel.find({ code: userRoleList[e], state: '0' }); if (role.length > 0) { const adminMenuList = role[0].adminMenuList; for (let i = 0; i < adminMenuList.length; i++) { const item = menu.filter(j => adminMenuList[i] === j.id)[0]; if (!menulist.includes(item) && item) { menulist.push(item); } } } } } } return { errcode: 0, errmsg: '', data: menulist }; } catch (error) { throw new Error('登录失败'); } } async captcha() { const captcha = svgCaptcha.createMathExpr({ // 翻转颜色 inverse: false, // 字体大小 fontSize: 36, // 噪声线条数 noise: 2, // 宽度 width: 80, // 高度 height: 30, }); // 保存到redis,忽略大小写 const code = captcha.text.toLowerCase(); this.ctx.session.code = code; this.ctx.response.type = 'image/svg+xml'; return captcha.data; } } module.exports = UserService;