Introduction: I have done a small project before, which used the graphic verification code, email and mobile phone number registration login, these three are basically now commonly used website verification method, now make a summary of the use of operation.

directory

  • The preparatory work
  • The principle of analytic
  • Methods to summarize
  • Online experience

The preparatory work

Installing dependency packages

Continue to open the demo folder created last time and download several dependency packages.

npm install svg-captcha nodemailer tencentcloud-sdk-nodejs --save
Copy the code
  • Svg-captcha can create graphic captcha
  • Nodemailer can send E-mail
  • Tencentcloud-sdk-nodejs can send SMS messages

Apply for preparing

In addition to the graphic verification code that can be used directly after installation, the other two must apply for authorization keys from email service providers and cloud computing operators.

Email application method

Recommended sites:

  • QQ email
  • Netease mail

Application steps for QQ Mailbox:

  • Open QQ mailbox to log in;

  • Click Settings, then open the Accounts TAB and click Enable POP3/SMTP service;

  • Click generate authorization code, send SMS, click I have sent, copy authorization code to a notepad inside;

Sending mail server: smtp.qq.com, using SSL, port number 465 or 587

Procedure for netease Email application:

  • Open email 163 and log in;

  • Click Settings, then open the Settings TAB and hit POP3/SMTP/IMAP;

  • Click POP3/SMTP service, send SMS, click I have sent, copy the authorization code to a notepad inside;

Mobile phone SMS application method

Tencent cloud is used this time to provide SMS services.

  • Open Tencent cloud official website to register and log in;
  • Open SMS product page, now is 618 activity period, buy SMS, about 1000, 38 yuan;

  • Then click the console to SMS console page to view the SMS package;

  • Next is SMS open configuration, refer to this article domestic SMS quick start;

After doing this, you get the application ID and template ID.

At this point, the whole application process is over.

The principle of analytic

Basically, several verification methods are similar, which can be summarized as the following steps:

  • Create or send the verification code content
  • Verify that it is correct

This step is described in detail below.

Create or send the verification code content

  • Graphic verification code

When we request an API address, first import the dependency package, configure the parameters, generate an SVG image, then respond to the request, send SVG data, and see an N-bit character image.

  • Email verification code

To import the mailbox dependency package, configure the parameters, and then call the send mail method, finally open the request to send email account, you can see an email.

  • Mobile phone

To introduce mobile phone dependency package, configure the parameters, and then call sending SMS method, finally open the request to send mobile phone SMS APP, you can see a message.

Verify that it is correct

  • Client submits parameters;
  • The server checks whether the input is correct and returns a message.

Methods to summarize

This section mainly encapsulates some common methods and then writes a script file.

Open the Demo folder, create a captCHA folder, and create config.js, mainly to put some configuration information; Create a new api.js to put some common methods.

Then create SVG, Email and phone folders and create index.js files for each folder.

The GET request is used to send the verification code, and the POST request is used to verify the verification code.

Commonly used method

Open the config.js file:

// Graphic, email, mobile verification code
const svg = {
    size: 4.// Verification code length
    ignoreChars: '012oOiILl'.// Exclude 0o1i from captcha characters
    noise: 1.// The number of interference lines
    fontSize: 52.color: true.// Turn on the text color
    // background:"#000",//
    width: 200.height: 80.time: 2*60,}const email = {
    service: 'qq'.port: 465.secure: true.user: '[email protected]'.pass: 'xxxxxxxxxxxxxx'.from: '[email protected]'.time: 2*60,}const phone = {
    secretId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'.secretKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'.reqMethod: "POST".reqTimeout: 30.endpoint: "sms.tencentcloudapi.com".signMethod: "HmacSHA256".region: "ap-shanghai".SmsSdkAppid: "XXXXXXX"./ / application id
    Sign: "DEMO".ExtendCode: "".SenderId: "".SessionContext: "".TemplateID: {
        eg: "XXXXXX",},time: 2*60,}module.exports = {
    svg,
    email,
    phone
}
Copy the code

Open the api.js file:

  • Detection method
// a method to check whether the verification code is correct;
CodeInfo Server verification code Session information *verifyInfo Verification code submitted by the client */
function check (res, req, infoType, codeInfo, verifyInfo) {
    let type = infoType == 'svg' ? 'svgInfo' :
    infoType == 'email' ? 'emailInfo' : 'phoneInfo';
    let typeText = infoType == 'svg' ? 'graphics' :
    infoType == 'email' ? 'email' : 'mobile phone';
    if (!Object.keys(codeInfo).length) {
        return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: 'Please get it again${typeText}Verification code! `}})}if(infoType ! ='phone') {
        codeInfo.code = codeInfo.code.toLowerCase();
    }
    if(! verifyInfo.code) {return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: `${typeText}Verification code cannot be empty! `}})}if (infoType == 'email' ||
    infoType == 'phone') {
        if(! verifyInfo[infoType]) {return res.json({
                code: 101.msg: 'get_fail'.data: {
                    info: `${typeText}Can't be empty! `}})}if(verifyInfo[infoType] ! = codeInfo[infoType]) {return res.json({
                code: 101.msg: 'get_fail'.data: {
                    info: `${typeText}Wrong account! `}}}})if (codeInfo.isVerify == 1) {
        return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: `${typeText}Captcha has been verified! `}})}if (((verifyInfo.time - codeInfo.time)/1000) > 60) {
        return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: `${typeText}The verification code has expired! `}})}if(verifyInfo.code ! = codeInfo.code) {return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: `${typeText}Verification code error! `
            }
        })
    }
    req.session[type].isVerify = 1;
    return res.json({
        code: 200.msg: 'get_succ'.data: {
            info: `${typeText}Verification code verified successfully! `}})}Copy the code
  • Sending email Messages
const nodemailer = require('nodemailer');
const emailConfig = require('./config').email;
// option configures parameters
function sendMail (res, option) {
    let transporter = nodemailer.createTransport({
        service: emailConfig.service,
        port: 465.secureConnection: true.auth: {
            user: emailConfig.user,
            pass: emailConfig.pass
        }
    })
    return transporter.sendMail(option, (error, info) = > {
        if (error) {
            return res.json({
                code: 101.msg: 'get_fail'.data: {
                    info: 'Sending failed, please try again! '.des: error
                }
            })
        } else {
            return res.json({
                code: 200.msg: 'get_succ'.data: {
                    info: 'Successfully sent, please note check! '}})}})}Copy the code
  • Sending text messages
/* * phoneNo Phone number * type Template type * phoneCode 6-digit verification code */
const tencentcloud = require('tencentcloud-sdk-nodejs');
const phoneConfig = require('./config').phone;

function sendSms (phoneNo, type, phoneCode) {
    // Import the client Models for the corresponding product module.
    const smsClient = tencentcloud.sms.v20190711.Client

    /* Instantiate the client object */ to request the product (in the case of SMS)
    const client = new smsClient({
        credential: {
            /* Required: Tencent cloud account key pair secretId, secretKey. * Read from an environment variable. Set these two values in the environment variable first. * You can also write dead key pairs in code, but be careful not to copy, upload, or share the code with others, * lest you compromise your property by revealing the key pair. * CAM key query: https://console.cloud.tencent.com/cam/capi * /
            secretId: phoneConfig.secretId,
            secretKey: phoneConfig.secretKey,
        },
        /* Required: Location information, you can directly fill in the string ap-guangzhou, or reference the default constant */
        region: phoneConfig.region,
        /* Optional: * Client configuration object, which can specify the timeout duration */
        profile: {
            /* the SDK uses tc3-hmac-sha256 by default. Do not change this field unless necessary
            signMethod: phoneConfig.signMethod,
            httpProfile: {
                /* The SDK uses POST by default. * If you must use the GET method, you can set it here. The GET method cannot handle some large requests */
                reqMethod: phoneConfig.reqMethod,
                /* The SDK has a default timeout, do not adjust it unless necessary * * Check the code if necessary for the latest default value */
                reqTimeout: phoneConfig.reqTimeout,
                /** * the SDK automatically specifies the domain name. Normally you do not need to specify a domain name, but if you are accessing the financial district service * you must manually specify the domain name, such as SMS's Shanghai financial district name: sms.ap-shanghai-fsi.tencentcloudapi.com */
                endpoint: phoneConfig.endpoint
            },
        },
    })

    /* Request parameters, depending on the interface called and the actual situation, can be further set request parameters * attributes may be basic type, may also reference another data structure * recommended to use IDE for development, you can easily jump to refer to the various interface and data structure documentation */
    const smsParams = {
        /* SMS application ID: SMS SdkAppid Specifies the actual SdkAppid generated after the application is added to the SMS console, for example, 1400006666 */
        SmsSdkAppid: phoneConfig.SmsSdkAppid,
        /* SMS signature content: Use UTF-8 encoding, must fill in the approved signature, signature information can be logged in [SMS console] to view */
        Sign: phoneConfig.Sign,
        /* EXTENSION of SMS code: disabled by default. To enable the extension, contact [SMS Helper] */
        ExtendCode: phoneConfig.ExtendCode,
        /* International/Hong Kong/Macao/Taiwan SMS senderID: Fill in the blank for domestic SMS, which is disabled by default. For enabling SMS, please contact [SMS Helper] */
        SenderId: phoneConfig.SenderId,
        /* User session content: can carry the user side ID and other context information, the server will return the same as */
        SessionContext: phoneConfig.SessionContext,
        +[Country or region code][Mobile phone number] * For example, +8613711112222, 86 indicates the country code, 13711112222 indicates the mobile phone number, and a maximum of 200 mobile phone numbers */
        PhoneNumberSet: [` + 86${phoneNo}`]./* Template ID: Enter the ID of the approved template. Template ID You can log in to the SMS console to view */
        TemplateID: phoneConfig.TemplateID[type],
        /* Template parameter: If there is no template parameter, set this parameter to empty */
        TemplateParamSet: [phoneCode],
    }
    // Calling the desired interface through the client object requires passing in the request object and the response callback function
    return new Promise(function (resolve, reject) {
        // Calling the desired interface through the client object requires passing in the request object and the response callback function
        client.SendSms(smsParams, function (err, response) {
            // An exception message is displayed
            if (err) {
                reject({
                    code: 102.info: 'get_fail'.data: {
                        info: 'Operation failed! '.detail: err
                    }
                });
            }
            resolve({
                code: 200.info: 'get_succ'.data: {
                    info: 'Operation successful! ', response } }); }); })}Copy the code

Captcha program

Graphic verification code

Write the following code:

const express = require('express');
const app = express();
const svgCaptcha = require('svg-captcha');
const config = require('.. /config');
const api = require('.. /api');

app.get('/svg'.(req, res) = > {
    
    // Create an image
    const svgImg = svgCaptcha.create(config.svg);
    req.session.svgInfo = {
        code: svgImg.text,
        time: new Date().getTime(),
        isVerify: 0};/ / send
    res.type('svg');
    res.status(200).send(svgImg.data);
});

app.post('/svg'.(req, res) = > {

    // Verify information
    letsvgInfo = {... req.session.svgInfo};let code = req.body.code;
    let verifyInfo = {
        code,
        time: new Date().getTime(),
    };

    // Check information
    return api.check(res, req, 'svg', svgInfo, verifyInfo);
});
Copy the code

Email verification code

const express = require('express');
const app = express();
const config = require('.. /config');
const api = require('.. /api');

app.get('/email'.(req, res) = > {

    // Validate parameters
    let email = req.query.email;
    if(! email) {return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: 'Email account cannot be empty! '}})}// Mailbox configuration
    letemailInfo = {... req.session.emailInfo};console.log('get email info:', emailInfo);
    let emailParams = {
        email,
        time: new Date().getTime(),
    };

    let emailConfig = config.email;
    let emailCode = (Math.random() * Math.pow(52.2)).toString(36).slice(4.10);

    let option = {
        from: 'Front End Laboratory' <${emailConfig.from}> `.to: email,
        subject: 'Mailbox verification code'.text: 'Dear users: Your email verification code is${emailCode}The validity of,${emailConfig.time/60}Minutes, please use as soon as possible! `.html: ' '
    }

    // Mailbox verification code detection
    if (emailInfo &&
        email === emailInfo.email &&
        ((emailInfo.time - emailParams.time)/1000)  < emailConfig.time) {
        return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: 'This email verification code has been sent! '}})}else {
        let emailInfo = {
            code: emailCode,
            email,
            time: new Date().getTime(),
            isVerify: 0};console.log('save email info:', emailInfo);
        req.session.emailInfo = emailInfo;
    }

    // Send an email
    return api.sendMail(res, option);
});

app.post('/email'.(req, res) = > {
    letemailInfo = { ... req.session.emailInfo };let code = req.body.code;
    let email = req.body.email;
    let verifyInfo = {
        email,
        code,
        time: new Date().getTime(),
    };
    return api.check(res, req, 'email', emailInfo, verifyInfo);
});
Copy the code

Mobile verification code

const express = require('express');
const app = express();
const config = require('.. /config');
const api = require('.. /api');

app.get('/phone'.async (req, res) => {
    // Validate parameters
    let phone = req.query.phone;
    if(! phone) {return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: 'Mobile phone account cannot be empty! '}})}// Phone configuration
    letphoneInfo = {... req.session.phoneInfo};console.log('get phone info:', phoneInfo);
    let phoneParams = {
        phone,
        time: new Date().getTime(),
    };

    let phoneConfig = config.phone;
    let phoneCode = Math.ceil(Math.random() * 1000000);

    // Mobile verification code detection
    if (phoneInfo &&
        phone === phoneInfo.phone &&
        ((phoneInfo.time - phoneParams.time)/1000)  < phoneConfig.time) {
        return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: 'The mobile verification code has been sent! '}})}else {
        let phoneInfo = {
            code: phoneCode,
            phone,
            time: new Date().getTime(),
            isVerify: 0};console.log('save phone info:', phoneInfo);
        req.session.phoneInfo = phoneInfo;
    }

    // Send the phone
    let phoneSet = await api.sendSms(phone, 'eg', phoneCode);
    if (phoneSet.code === 200) {
        return res.json({
            code: 200.msg: 'get_succ'.data: {
                info: 'Successfully sent, please note check! '.err: phoneSet.data.detail
            }
        })
        
    } else {
        return res.json({
            code: 101.msg: 'get_fail'.data: {
                info: 'Sending failed, please try again! '}}}})); app.post('/phone'.(req, res) = > {
    letphoneInfo = { ... req.session.phoneInfo };let code = req.body.code;
    let phone = req.body.phone;
    let verifyInfo = {
        phone,
        code,
        time: new Date().getTime(),
    };
    return api.check(res, req, 'phone', phoneInfo, verifyInfo);
});
Copy the code

Online experience

If you want to try this out, there’s a gadget app for registration and login, as well as graphical, email, and mobile authentication.

Write in the last

The above is my development of some experience summary, if there is any problem, please contact me via email, I will take time to check, correct the wrong place.