Results show

The style may be a little ugly, please don’t mind

The technology used

Express, Vue, Redis, Axios

Function implementation

Image verification code generation

Svg-captcha is a module that can generate graphic verification codes

Download the SVG-CAPtCHA module

npm i svg-captcha -S
Copy the code

Introduced in nodeJS

const code = require("svg-captcha");
Copy the code

The module is then configured and exported

const code = require("svg-captcha");
function createCode() {
    return code.create({
        size: 4.ignoreChars: "0o1iIl".noise: 3.color: true.background: "#fff".fontSize: 60
    });
}
module.exports = createCode;
Copy the code

After the module is exported, the module that generates the image verification code is introduced into the back-end routing module

const captcha = require("./Code")
Copy the code

An instance of SVG-CAPtCHA gives us two attributes

  • Data: indicates the verification code SVG
  • Text: indicates the verification code text

We want the front end to display SVG images, not text text, because if you want to simulate login crawler too easy.

Then access the captcha interface address, you can see the picture.

Front-end page code

All the frameworks and tools I cite are CND

HTML part

<div id="app">
    <p><label>User name:</label><input type="text" ref="username" value="Wick"></p>
    <p><label>Password:</label><input type="text" ref="password" value="123456"></p>
    <p id="code">
        <label>Verification code:</label>
        <input ref="codeValue" type="text">
        <img @click="getCode" :src="codeImg" alt="">
    </p>
    <button id="login" @click="login">The login</button>
</div>
Copy the code

Js part

axios.defaults.baseURL = "http://localhost:10086";
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.withCredentials = true;
axios.interceptors.request.use(config= > {
    return config;
})
const app = new Vue({
    el: "#app".data: {
        codeImg: `http://localhost:10086/code? t=The ${new Date().getTime()}`
    },
    methods: {
        getCode() {
            // Add the timestamp to switch the captcha
            this.codeImg = `http://localhost:10086/code? t=The ${new Date().getTime()}`;
            this.$refs.codeValue.value = "";
        },
        login() {
            let username = this.$refs.username.value;
            let password = this.$refs.password.value;
            let code = this.$refs.codeValue.value;
            let data = {
                username,
                password: CryptoJS.AES.encrypt(password, username).toString(),   // Password encryption
                code
            }
            axios.post("/login", Qs.stringify(data)).then(res= > {
                alert(res.data.msg);
                if(res.data.success === "ok") {
                    window.location = "/Home.html"; }})}}});Copy the code

Introduction of express – session

Native NodeJS does not provide session functionality, so we had to introduce the third-party module Express-Session

Download express – session

npm i -S express-session
Copy the code

Express nodejs in the session

const session = require("express-session");
Copy the code

Middleware Settings for detailed configuration follow the Express-session documentation

app.use(session({
    secret: "WickYo".// Sign cookies
    name: "session".// Cookie name, default connect.sid
    resave: false.// Force the session to be saved back to the session container
    rolling: true.// Force a session identifier cookie on each response
    cookie: {
        / / for 5 minutes
     	maxAge: 300000}}))Copy the code

After configuration, the response of the page will have this session

Check the cookies in the Application

The lifetime of the session is used to determine whether the verification code is invalid. When the session expires, the verification code will also be invalid, and you need to switch authentication for login

Import Redis and set the verification code

Download the Redis module

npm i redis -S
Copy the code

Nodejs introduced in

const redis = require("redis");
Copy the code

To configure Redis, here is a simple configuration, the details of the redis document

const client = redis.createClient({
    host: "192.168.56.101"./ / redis address
    port: 6379	/ / the port number
})
// Listen for connection events
client.on("connect", error => {
    if(! error) {console.log("connect to redis")}})// Listen for error events
client.on("error", error => {
    throw new Error(error)
})
Copy the code

Encapsulating set method

function setString(key, value, expire) {
    return new Promise((resolve, reject) = > {
        client.set(key, value, (error, replay) => {
            if(error) {
                reject("Setup failed")}if(expire) {
                client.expire(key, expire);
            }
            resolve("Setup successful")}); })}Copy the code

Wrap the GET method

function getString(key) {
    return new Promise((resolve, reject) = > {
        if(key) {
            client.get(key, (error, replay) => {
                if(error) {
                    reject(` access${key}Failure `) } resolve(replay); })}})}Copy the code

Finally, the method is exported.

module.exports = {
    setString,
    getString
}
Copy the code

The set and GET methods are encapsulated above, so we can set values in Redis.

After the previous Express-session configuration, we load the captco image and set the cookie(holding the sessionID value) when we enter the page, and then take the cookie with us when we log in. SessionID = key and svG-CAPtCHA text = value

Note: sessionID is injected after express-session is used

Implementation of Login Function

For convenience, instead of connecting to the database, create a local file to use as the user’s password

Go straight to code

Router.post("/login", (req, res) => {
    let username = req.body.username;
    let password = CryptoJS.AES.decrypt(req.body.password, username).toString(CryptoJS.enc.Utf8);   / / decryption
    let code = req.body.code.toLowerCase();
    if(! req.signedCookies.session) { res.send({success: "no".msg: "Verification code expired"})
        return;
    }
    // Redis encapsulates the method
    getString(req.signedCookies.session).then(data= > {
        // signedCookies are signedCookies
        console.log(data)
        if(code === data) {
            console.log("The verification code is correct")
            / / read the file
            fs.readFile(__dirname + "/.. /user.conf"."utf8", (err, data) => {
                let dataArr = data.toString().split("=");
                if(username === dataArr[0]) {
                    if(password === dataArr[1]) {
                        // Set a cookie based on the login user name and specify that the cookie can only survive for 30 minutes
                        res.cookie("uid", username, {maxAge: 300000})
                        res.send({success: "ok".msg: "Login successful"})
                        return;
                    }
                }
                res.send({success: "no".msg: "Wrong username or password"})})}else {
            res.send({success: "no".msg: "Verification code error"})
        }
    }).catch(err= > {
        console.log(err)
    })
})
Copy the code

The introduction of the cookie – parser

Cookie -parse can be introduced to decrypt cookies

Middleware Setup

app.use(cookieParser(secret))
Copy the code

Once configured, cookies encrypted with the secret specified can be parsed

Gets the POST request parameters

We can’t get the POST parameters directly. We need to install the Body-Parser module to get them

npm i -S body-parser
Copy the code

Configure the body – parser

app.use(bodyParser.urlencoded({ extended: false }))	Analytical application / / / x - WWW - form - urlencoded
Copy the code

After configuration, we can get the request body

What is a Signed cookie?

Cookie has a disadvantage, is visible in the browser, and can be modified, if we directly store sensitive information in the cookie, then anyone can be visible, anyone can modify it, which is very insecure.

Because it is not secure, you need Signed cookies to encrypt it to prevent certain information from being leaked.

We manually decrypt the encrypted cookie

The decrypted value is actually the sessionID at the time of obtaining the verification code.

So, we can get cookies by req.signedcookies because cookie-Parser decrypts them for us.

This article is available at github: github.com/OnlyWick/Fu…

Please point out any mistakes in time!