Node.js Part 12: random verification code of pictures

Keywords: Programming Session npm xml

1. Why random verification code is needed

Prevent malicious machine registration. The role of verification code: effectively prevent this problem from a specific registered user using a specific program brute force to try to login, in fact, verification code is the current way of many websites, using a relatively simple way to achieve this function. Although it's a bit more difficult to log in, it's still necessary and important for the community.

Two Node.js Implementation of random verification code

Install third party package

npm install svg-captcha --save

file: https://www.npmjs.com/package/svg-captcha

Code demonstration

back-end program

const koa = require('koa')
const router = require('koa-router')()
// Import koa session module
const session = require('koa-session')
// Import svgCaptcha
const svgCaptcha = require('svg-captcha');

const app = new koa()

// Configure session
app.keys = ['some secret hurr'];
const CONFIG = {
  key: 'koa:sess', //cookie key (default is koa:sess) 
  maxAge: 86400000, // Expiration time of cookie maxAge in ms (default is 1 days) 
  overwrite: true, //Whether overwrite is allowed (default true) 
  httpOnly: true, //Whether only the server side can access httpOnly or not (default true) 
  signed: true, //Signature default true 
  rolling: false, //Force cookies on every request, which resets the cookie expiration time (default: false) 
  renew: false, //(boolean) renew session when session is nearly expired, 
};
app.use(session(CONFIG, app));

// Verification code request path
router.get('/imgcode', async (ctx) => {
  const captcha = svgCaptcha.create(
    {
      size: 6,   // Number of verification code characters
      fontSize: 20, // Text size
      width: 100,   // image width
      height: 40,   // Picture height
      noise:5,      // Number of obscured lines
      background: "#cc9966 "/ / background color
    });
  ctx.session.code = captcha.text;   // Store random characters in session
  ctx.response.type = 'image/svg+xml';  // Set the type of response
  ctx.body = captcha.data;  
})

// Register route
app.use(router.routes())
// Function: This is the recommended use of official documents. We can see router.allowedMethods() used for route matching router.routes (after), so when all routing middleware finally calls. ctx.status  Set response response header
app.use(router.allowedMethods());

app.listen(80)

Front end program

  <img id="imgcode" style="width: 300px;cursor: pointer;" src="http://localhost/imgcode" alt="">
  <script>
    imgcode.onclick = function(){
      imgcode.src = 'http://localhost/imgcode?random' + Date.now()
    }
  </script>

Posted by Naez on Wed, 13 May 2020 10:49:20 -0700