1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- const svgCaptcha = require('svg-captcha');
- const md5 = require("md5");
- const API = require("../../../lib/API");
- const { BaseStdResponse } = require("../../../BaseStdResponse");
- const Redis = require('../../../plugin/DataBase/Redis');
- // 生成图片验证码
- class ImageCaptcha extends API {
- constructor() {
- super();
- this.setMethod("GET");
- this.setPath("/User/ImageCaptcha");
- }
- async onRequest(req, res) {
- const options = {
- size: 4, // 4个字母
- noise: 2, // 干扰线2条
- color: true,
- background: "#666",
- }
- const captcha = svgCaptcha.create(options) //字母和数字随机验证码
- let { text, data } = captcha
- text = text.toLowerCase()
- data = Buffer.from(data).toString('base64');
- // 构建Base64编码的Data URL
- data = `data:image/svg+xml;base64,${data}`;
- const id = md5(Date.now() + text);
- try {
- await Redis.set(`captcha:${id}`, text, {
- EX: 600
- });
- } catch (err) {
- this.logger.error(`获取图片验证码失败!${err.stack}`);
- return res.json({
- ...BaseStdResponse.DATABASE_ERR,
- msg:'获取图片验证码失败!'
- })
- }
- res.json({
- ...BaseStdResponse.OK,
- data: {
- img: data,
- id
- }
- })
- }
- }
- module.exports.ImageCaptcha = ImageCaptcha;
|