@solarwinter/captchajs
TypeScript icon, indicating that this package has built-in type declarations

0.1.7 • Public • Published

captchajs

CircleCI

CaptchaJs is a JavaScript library with the aim of making it easy to use the captchas.net service.

Installation

yarn add @solarwinter/captchajs

or

npm install @solarwinter/captchajs

Usage

For testing and development you can use the example values seen on the bottom of the captchas.net webpage:

  • username demo
  • secret key secret
  • random string RandomZufall

Load the username and secret key into your program - the common method is via .env file - and use them to initialise CaptchaJs.

import { CaptchaJs } from "@solarwinter/captchajs";

const captcha = new CaptchaJs({ client: process.env.CAPTCHAS_CLIENT,
                                secret: process.env.CAPTCHAS_SECRET });
const random = captcha.getRandomString();
const imageUrl = captcha.getImageUrl({ randomString: random })
const audioUrl = captcha.getAudioUrl({ randomString: random })

Those URLs need to be passed to the page shown to the user. The exact method of doing so will vary; if you're using ERB (similar to Jinja or Mustache) then it might look like this:

<div>
    <img src="<%= captchaImageUrl %>" alt="Captcha image">
    <a href="<%= captchaAudioUrl %>" alt="Audio version of captcha">Captcha audio</a>
    <label for="captchaPassword">
        Captcha text?
    </label>
    <input type="hidden" name="randomString" value="<%= randomString %>"/>
    <input name="captchaPassword" type="text" required/>
</div>

When the user hits Submit on the form, the fields should be POSTed back to your server application. There you can check the captcha string - for example:

if (!captcha.validateRandomString(data.randomString)) {
  console.log(`Error validating random string ${data.randomString}`);

  // At this point you can re-render the contact page, for example with error text:
  //   "That captcha has expired or already been used"
} else if (!captcha.verifyPassword(data.randomString, data.captchaPassword)) {
  console.log(`Error verifying password ${data.captchaPassword}`);

  // At this point you can re-render the contact page, for example with error text:
  //   "Sorry, you got the captcha text wrong. Please try again."
} else {
  console.log("Captcha passed!");
  // Do something here!
}

Before you can use this package in production you need to register with the captchas.net service. When you've registered you should receive an email from captchas.net containing your client ID (or 'user name') and the shared secret.

Package Sidebar

Install

npm i @solarwinter/captchajs

Weekly Downloads

0

Version

0.1.7

License

MIT

Unpacked Size

85.5 kB

Total Files

27

Last publish

Collaborators

  • pwalker