admin.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // 用户登录
  2. /* eslint-disable array-callback-return */
  3. 'use strict';
  4. const Controller = require('egg').Controller;
  5. const filePath = require('../../config/filespath');
  6. class AdminController extends Controller {
  7. async login() {
  8. const { ctx, app } = this;
  9. const { userName, password } = ctx.request.body;
  10. const configJson = require(filePath.configJson);
  11. const data = configJson.admin.filter(p => p.userName === userName);
  12. console.log(data);
  13. let msg;
  14. if (data.length <= 0) {
  15. msg = { errcode: -1, errmsg: '用户不存在' };
  16. } else {
  17. if (data[0].password === password) {
  18. const token = app.jwt.sign({ userName, name: data[0].name }, app.config.jwt.secret, {
  19. expiresIn: 60 * 60 * 60,
  20. });
  21. msg = { errcode: 0, errmsg: '', token, userName, name: data[0].name };
  22. } else {
  23. msg = { errcode: -1, errmsg: '密码错误' };
  24. }
  25. }
  26. ctx.body = msg;
  27. }
  28. async editPwd() {
  29. const { ctx } = this;
  30. const { userName, password, newpassword } = ctx.request.body;
  31. const configJson = require(filePath.configJson);
  32. const data = configJson.admin.filter(p => p.userName === userName);
  33. let msg;
  34. try {
  35. if (data.length <= 0) {
  36. msg = { errcode: -1, errmsg: '用户不存在' };
  37. } else {
  38. if (data[0].password === password) {
  39. configJson.admin.map(p => {
  40. if (p.userName === userName) {
  41. p.password = newpassword;
  42. }
  43. });
  44. const jsonstr = JSON.stringify(configJson);
  45. await this.service.fileshandler.write({ filePath: filePath.configJson, str: jsonstr });
  46. msg = { errcode: 0, errmsg: '' };
  47. } else {
  48. msg = { errcode: -1, errmsg: '密码错误' };
  49. }
  50. }
  51. ctx.body = msg;
  52. } catch (error) {
  53. const body = { errcode: -1003, errmsg: '密码修改失败', error };
  54. throw new Error(JSON.stringify(body));
  55. }
  56. }
  57. }
  58. module.exports = AdminController;