ImageCaptcha.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const svgCaptcha = require('svg-captcha');
  2. const md5 = require("md5");
  3. const API = require("../../../lib/API");
  4. const { BaseStdResponse } = require("../../../BaseStdResponse");
  5. const Redis = require('../../../plugin/DataBase/Redis');
  6. // 生成图片验证码
  7. class ImageCaptcha extends API {
  8. constructor() {
  9. super();
  10. this.setMethod("GET");
  11. this.setPath("/User/ImageCaptcha");
  12. }
  13. async onRequest(req, res) {
  14. const options = {
  15. size: 4, // 4个字母
  16. noise: 2, // 干扰线2条
  17. color: true,
  18. background: "#666",
  19. }
  20. const captcha = svgCaptcha.create(options) //字母和数字随机验证码
  21. let { text, data } = captcha
  22. text = text.toLowerCase()
  23. data = Buffer.from(data).toString('base64');
  24. // 构建Base64编码的Data URL
  25. data = `data:image/svg+xml;base64,${data}`;
  26. const id = md5(Date.now() + text);
  27. try {
  28. await Redis.set(`captcha:${id}`, text, {
  29. EX: 600
  30. });
  31. } catch (err) {
  32. this.logger.error(`获取图片验证码失败!${err.stack}`);
  33. return res.json({
  34. ...BaseStdResponse.DATABASE_ERR,
  35. msg:'获取图片验证码失败!'
  36. })
  37. }
  38. res.json({
  39. ...BaseStdResponse.OK,
  40. data: {
  41. img: data,
  42. id
  43. }
  44. })
  45. }
  46. }
  47. module.exports.ImageCaptcha = ImageCaptcha;