/ example / index.js
index.js
 1  'use strict';
 2  
 3  const express = require("express");
 4  const Mustache = require('mustache');
 5  
 6  const { CaptchaJs } = require("../build");
 7  // const { CaptchaJs } = require("@solarwinter/CaptchaJs");
 8  
 9  const captcha = new CaptchaJs({
10    client: "demo",
11    secret: "secret"
12  });
13  
14  // Three {} means that Mustache will leave the HTML tags alone.
15  const page = "<html><head></head><body>{{{content}}}</body></html>";
16  const app = express();
17  
18  app.use(require("body-parser").urlencoded({ extended: true }));
19  app.get("/", sendForm);
20  app.post("/", processForm);
21  app.listen(8000);
22  
23  function sendForm(req, res) {
24    const random = captcha.getRandomString();
25    const imageUrl = captcha.getImageUrl({ randomString: random })
26    const audioUrl = captcha.getAudioUrl({ randomString: random })
27  
28    const content = `<form method="POST">
29            <img src="${imageUrl}" alt="Captcha image">
30            <a href="${audioUrl}" alt="Audio version of captcha">Captcha audio</a>
31            <label for="captchaText">
32                Captcha text?
33            </label>
34            <input type="hidden" name="randomString" value="${random}" />
35            <input name="captchaText" type="text" required />
36            <button type="submit">Click me</button>
37        </form>`;
38    res.send(Mustache.render(page, { content: content }));
39  };
40  
41  function processForm(req, res) {
42    let content;
43    const randomString = req.body.randomString;
44    const captchaText = req.body.captchaText;
45  
46    if (!captcha.validateRandomString(randomString)) {
47      content = '<p>That captcha has expired or already been used. <a href="/">Please try again.</a></p>';
48    } else if (!captcha.verifyPassword(randomString, captchaText)) {
49      content = '<p>Sorry, you got the captcha text wrong. <a href="/">Please try again.</a></p>';
50    } else {
51      content = '<p>Well done, you got it right! <a href="/">Play again?</a></p>';
52    }
53  
54    res.send(Mustache.render(page, { content: content }));
55  }