pwdlogin.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const sm3 = require('sm3');
  4. const assert = require('assert');
  5. const jsonwebtoken = require('jsonwebtoken');
  6. const svgCaptcha = require('svg-captcha');
  7. class LoginController extends Controller {
  8. constructor(ctx) {
  9. super(ctx);
  10. this.model = this.ctx.model.AdminUser;
  11. }
  12. // 用户名密码登录
  13. async auth() {
  14. const { userName, password, uuid, code } = this.ctx.request.body;
  15. assert(userName, '缺少用户名');
  16. assert(password, '缺少密码');
  17. assert(uuid, '缺少uuid');
  18. assert(code, '缺少验证码');
  19. const { jwt } = this.app.config;
  20. let msg;
  21. const ban = await this.app.redis.get(userName);
  22. if (ban) {
  23. if (ban >= this.app.config.ban) {
  24. this.ctx.body = { errcode: -1001, errmsg: '限制登录, 请在5分钟后重试', data: '' };
  25. return;
  26. }
  27. await this.app.redis.set(userName, Number(ban) + 1, 'EX', this.app.config.bantime);
  28. } else {
  29. await this.app.redis.set(userName, 1, 'EX', this.app.config.bantime);
  30. }
  31. // 验证码
  32. const redisCode = await this.app.redis.get(uuid);
  33. if (!redisCode) {
  34. this.ctx.body = { errcode: -1001, errmsg: '验证码已失效', data: '' };
  35. return;
  36. }
  37. if (code !== redisCode) {
  38. this.ctx.body = { errcode: -1001, errmsg: '验证码错误', data: '' };
  39. return;
  40. }
  41. const res = await this.model.findOne({ userName });
  42. if (!res) {
  43. this.ctx.body = { errcode: -1001, errmsg: '用户不存在', data: '' };
  44. return;
  45. }
  46. // 密码
  47. const pwd = sm3(`${password}:${res.salt}`);
  48. if (res.password !== pwd) {
  49. this.ctx.body = { errcode: -1001, errmsg: '密码错误', data: '' };
  50. return;
  51. }
  52. const token = jsonwebtoken.sign({ ...res }, jwt.secret, { expiresIn: jwt.expiresIn, issuer: jwt.issuer });
  53. const userinfo = { userName, name: res.name || null, phone: res.phone || null, id: res._id || null };
  54. if (token && userinfo) msg = { errcode: 0, errmsg: '', data: { userinfo, token } };
  55. this.ctx.body = msg;
  56. }
  57. // 获取验证码
  58. async get_verification_code() {
  59. const uuid = this.ctx.query.uuid;
  60. const captcha = svgCaptcha.createMathExpr({
  61. // 翻转颜色
  62. inverse: false,
  63. // 字体大小
  64. fontSize: 36,
  65. // 噪声线条数
  66. noise: 2,
  67. // 宽度
  68. width: 80,
  69. // 高度
  70. height: 30,
  71. });
  72. // 保存到redis,忽略大小写
  73. const code = captcha.text.toLowerCase();
  74. await this.app.redis.set(uuid, code, 'EX', 60 * 5);
  75. this.ctx.response.type = 'image/svg+xml';
  76. this.ctx.body = captcha.data;
  77. }
  78. }
  79. module.exports = LoginController;