scnario commited on
Commit
2b65d87
·
verified ·
1 Parent(s): 31278d6

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +24 -7
server.js CHANGED
@@ -1,25 +1,42 @@
1
  const express = require("express");
2
- const captcha = require("captcha");
 
3
  const fs = require("fs");
4
  const os = require("os");
5
  const path = require("path");
 
6
 
7
  const app = express();
8
  const tempDir = os.tmpdir();
9
 
10
- app.get("/captcha", (req, res) => {
11
- const captchaCode = Math.random().toString(36).substring(2, 6).toUpperCase();
12
- const captchaImage = captcha.create({ width: 150, height: 50, text: captchaCode });
13
 
14
- const fileName = `temp_${Math.random().toString(36).substring(2, 6).toUpperCase()}.png`;
 
 
 
 
 
 
 
 
15
  const filePath = path.join(tempDir, fileName);
16
 
17
- fs.writeFile(filePath, captchaImage.buffer, (err) => {
 
 
 
 
 
 
 
18
  if (err) {
19
  return res.status(500).json({ error: "Failed to save captcha" });
20
  }
21
  res.json({
22
- answer: captchaCode,
23
  url: filePath
24
  });
25
  });
 
1
  const express = require("express");
2
+ const svgCaptcha = require("svg-captcha");
3
+ const { createCanvas, loadImage } = require("canvas");
4
  const fs = require("fs");
5
  const os = require("os");
6
  const path = require("path");
7
+ const crypto = require("crypto");
8
 
9
  const app = express();
10
  const tempDir = os.tmpdir();
11
 
12
+ function generateRandomHex(length) {
13
+ return crypto.randomBytes(length).toString("hex");
14
+ }
15
 
16
+ app.get("/captcha", async (req, res) => {
17
+ const captcha = svgCaptcha.create({
18
+ size: 6,
19
+ ignoreChars: "0oO1iIl",
20
+ noise: 2,
21
+ color: true
22
+ });
23
+
24
+ const fileName = `${generateRandomHex(16)}.png`;
25
  const filePath = path.join(tempDir, fileName);
26
 
27
+ const canvas = createCanvas(200, 80);
28
+ const ctx = canvas.getContext("2d");
29
+ const img = await loadImage(`data:image/svg+xml;base64,${Buffer.from(captcha.data).toString("base64")}`);
30
+
31
+ ctx.drawImage(img, 0, 0, 200, 80);
32
+ const buffer = canvas.toBuffer("image/png");
33
+
34
+ fs.writeFile(filePath, buffer, (err) => {
35
  if (err) {
36
  return res.status(500).json({ error: "Failed to save captcha" });
37
  }
38
  res.json({
39
+ answer: captcha.text,
40
  url: filePath
41
  });
42
  });