/ README.md
README.md
1 # captchajs 2 3 [](https://circleci.com/gh/arafel/CaptchaJs) 4 5 CaptchaJs is a JavaScript library with the aim of making it easy to 6 use the [captchas.net](http://captchas.net) service. 7 8 ### Installation 9 10 ``` 11 yarn add @solarwinter/captchajs 12 ``` 13 14 or 15 16 ``` 17 npm install @solarwinter/captchajs 18 ``` 19 20 ### Usage 21 22 For testing and development you can use the example values seen on the bottom of the 23 [captchas.net webpage](http://captchas.net/registration/): 24 25 * username `demo` 26 * secret key `secret` 27 * random string `RandomZufall` 28 29 Load the username and secret key into your program - the common method is via .env file - and use 30 them to initialise CaptchaJs. 31 32 ```typescript 33 import { CaptchaJs } from "@solarwinter/captchajs"; 34 35 const captcha = new CaptchaJs({ client: process.env.CAPTCHAS_CLIENT, 36 secret: process.env.CAPTCHAS_SECRET }); 37 const random = captcha.getRandomString(); 38 const imageUrl = captcha.getImageUrl({ randomString: random }) 39 const audioUrl = captcha.getAudioUrl({ randomString: random }) 40 ``` 41 42 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 43 ERB (similar to Jinja or Mustache) then it might look like this: 44 45 ```html 46 47 <div> 48 <img src="<%= captchaImageUrl %>" alt="Captcha image"> 49 <a href="<%= captchaAudioUrl %>" alt="Audio version of captcha">Captcha audio</a> 50 <label for="captchaPassword"> 51 Captcha text? 52 </label> 53 <input type="hidden" name="randomString" value="<%= randomString %>"/> 54 <input name="captchaPassword" type="text" required/> 55 </div> 56 ``` 57 58 When the user hits Submit on the form, the fields should be POSTed back to your server application. There you can check 59 the captcha string - for example: 60 61 ```typescript 62 if (!captcha.validateRandomString(data.randomString)) { 63 console.log(`Error validating random string ${data.randomString}`); 64 65 // At this point you can re-render the contact page, for example with error text: 66 // "That captcha has expired or already been used" 67 } else if (!captcha.verifyPassword(data.randomString, data.captchaPassword)) { 68 console.log(`Error verifying password ${data.captchaPassword}`); 69 70 // At this point you can re-render the contact page, for example with error text: 71 // "Sorry, you got the captcha text wrong. Please try again." 72 } else { 73 console.log("Captcha passed!"); 74 // Do something here! 75 } 76 ``` 77 78 Before you can use this package in production you need to [register with the 79 captchas.net](http://captchas.net/registration/) service. When you've registered you should receive an email from 80 captchas.net 81 containing your client ID (or 'user name') and the shared secret.