Advertisement
Guest User

Untitled

a guest
Dec 9th, 2024
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. const globalClient = require('../../../client.js');
  2. const svgCaptcha = require('svg-captcha');
  3. const sharp = require('sharp');
  4.  
  5. class CaptchaGenerator {
  6. constructor() {
  7. this.options = {
  8. size: 6, // Length of captcha text
  9. noise: 8, // Number of noise lines
  10. color: true, // Colors enabled
  11. background: 'transparent',
  12. width: 300,
  13. height: 150,
  14. fontSize: 100,
  15. charPreset: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' // Characters to use
  16. };
  17. }
  18.  
  19. /**
  20. * Generate a captcha with both text and image
  21. * @returns {Promise<{text: string, image: Buffer}>} Captcha text and PNG buffer
  22. */
  23. async generate() {
  24. try {
  25. // Generate SVG captcha
  26. const captcha = svgCaptcha.create(this.options);
  27.  
  28. // Convert SVG to PNG using sharp
  29. const pngBuffer = await sharp(Buffer.from(captcha.data))
  30. .composite([{
  31. input: Buffer.from(`<svg>
  32. <rect width="100%" height="100%" fill="white"/>
  33. </svg>`),
  34. blend: 'dest-over'
  35. }])
  36. .png()
  37. .toBuffer();
  38.  
  39. return {
  40. text: captcha.text, // The captcha solution
  41. imageBuffer: pngBuffer // PNG buffer that can be used to save or send the image
  42. };
  43. } catch (error) {
  44. throw new Error(`Failed to generate captcha: ${error.message}`);
  45. }
  46. }
  47.  
  48. /**
  49. * Customize captcha generation options
  50. * @param {Object} newOptions - Options to override defaults
  51. */
  52. setOptions(newOptions) {
  53. this.options = {
  54. ...this.options,
  55. ...newOptions
  56. };
  57. }
  58. }
  59.  
  60. module.exports = {
  61. name: 'captchaGenerator',
  62. priority: 0,
  63. initialize: async () => {
  64. const generator = new CaptchaGenerator();
  65. const namespace = globalClient.registerNamespace('captcha');
  66.  
  67. namespace.generate = generator.generate.bind(generator);
  68. namespace.setOptions = generator.setOptions.bind(generator);
  69.  
  70. return true;
  71. }
  72. };
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement