node. JS mailbox registration, activation and login related cases

Time:2022-1-21

email-verify

Specific detailed code GitHub
In addition to the third-party login access, the current login system mainly includes SMS login and email login. According to the characteristics of the current real name system, there are more SMS login, but some will use email login.
This article is mainly about the relevant cases of email login. Generally speaking, users use email to register. When the registration is successful, they will send an email to the registered user for activation. Of course, this email has certain timeliness. After activation, the user can normally use the relevant functions. If they are not activated, they will be prompted if they are not activated when logging in. Do you need to send an email to activate them.

1. Use tools

  • node v8.5.0
  • mongodb
  • ioredis
  • postman

2. Project structure

node. JS mailbox registration, activation and login related cases

The meaning of key documents is illustrated in the figure

3. User registration interface

When a user registers, first check whether the necessary fields are passed in and whether the mailbox password meets the specification, and then check whether the mailbox has been registered. When the registration is successful, an email will be sent to the user to activate the account. The content of the email sent is a link, including the user’s mailbox and code. Code sets the expiration time using reids. (when not activated, the user status is 0 and the activation status is 1)
The routes registered in routes are as follows:

 //user_regist
router.post('/user_regist', userCtrl.user_regist);

Some codes registered in controllers are as follows:

try {
        const user = await findUserAsyc({ 'useremail': user_email });// Verify that the user is registered
        if (user) {
            respondData.status = 10002;
            respondData. Error = "mailbox registered";
            return res.json(respondData);
        }
        //User parameters
        const userpassword = md5(user_password);
        const userInfo = {
            useremail: user_email,
            username: user_name,
            userpwd: userpassword,
            status: 0,
            create_time: Date.now('YYYY-MM-DD')
        };
        //New user
        console.log("newGuess.save userInfo-->" + JSON.stringify(userInfo));
        const newUser = new UserModel(userInfo);
        newUser.save(function (err, data) {
            if (err) {
                console.log("newGuess.save err-->" + JSON.stringify(err));
                respondData.status = "00001";
                respondData.error = "mongodb system error";
                return res.json(respondData);
            }
            console.log("newGuess.save data -->" + JSON.stringify(data));
            let userEmail = data.useremail;
            let sendEmail = sendUserEmail(userEmail);
            console.log("sendEmail:" + sendEmail);
            respondData. MSG = "new user registration succeeded and email activation sent successfully";
            return res.json(respondData);
        });
    } catch (error) {
        //Error handling
        console.log("controllers/UserController.js/user_regist error -->" + JSON.stringify(error));
        respondData.error = error;
        return res.json(respondData);
    }

Email sending part code

var config_email = {
        host: 'smtp.163.com',
        Post: 25, // SMTP port
        //Secureconnection: true, // use SSL
        auth: {
            user: '[email protected]',
            //The password here is not the QQ password, but the SMTP password you set
            pass: 'wwf'
        }
    };
    var transporter = nodemailer.createTransport(config_email);

    var html = "<div>http://127.0.0.1:3000?code=" + code + "&account=" + cnd + "</div>";
    console.log(html);
    var data = {
        from: ' [email protected] ', // sending address
        To: CND, // recipient list
        Subject: 'hello Feng', // Title

        //Text: HTML // Title // only one is supported for both text and HTML
        HTML: HTML // HTML content
    };
    console.log(data);
    transporter.sendMail(data, function (err, info) {
        if (err) {
            return (err);
        }
        console.log(info.response);
        return (info.response);

    });

Simulate registration using postman
node. JS mailbox registration, activation and login related cases

The screenshot at this time just intercepts the message sent to the mailbox. It’s perfect

When the user is not activated, the status of this user in the database is = 0; As shown in the figure:
Database user information
node. JS mailbox registration, activation and login related cases

4. User mailbox activation

By clicking the link in the mailbox, the mailbox will be activated. When the mailbox and code do not match, the mailbox mismatch message will be returned. When the code expires, the code expiration message will be returned. When the user has been activated, he will be told that it has been activated and do not activate again. When the user information does not have the above conditions, he will be prompted that the activation is successful.
Routes activated in routes are as follows:

//user_activation
router.get('/user_activation', userCtrl.user_activation);

Some codes registered in controllers are as follows:

try {
        let codeVal = await Jtoken(code);
        if (!codeVal) {
            respondData. Error = "code is invalid, please re send email to activate";
            return res.json(respondData);
        }
        let userinfo = JSON.parse(codeVal);
        if (userinfo.userEmail !== user_email) {
            respondData. Error = "the mailbox is incorrect";
            return res.json(respondData);
        }
        const user = await findUserAsyc({ 'useremail': user_email });// Verify that the user is registered
        if (user) {
            if (user.status === 0) {
                UserModel.update({ 'useremail': user_email }, { '$set': { status: 1 } }, function (err, results) {
                    if (err) {
                        console.log("UserModel.update err-->" + JSON.stringify(err));
                        respondData.status = "00001";
                        respondData.error = "mongodb system error";
                        return res.json(respondData);
                    }
                    respondData. MSG = "mailbox activation succeeded";
                    return res.json(respondData);
                })
            } else if (user.status === 1) {
                respondData. MSG = "this mailbox has been activated, please do not activate it again";
                return res.json(respondData);
            }
        }
    } catch (error) {
        //Error handling
        console.log("controllers/UserController.js/user_regist error -->" + JSON.stringify(error));
        respondData.error = error;
        return res.json(respondData);
    }

Simulation activation using postman succeeded
node. JS mailbox registration, activation and login related cases
Simulate activation code failure using postman
node. JS mailbox registration, activation and login related cases
User information of the database when activation is successful
node. JS mailbox registration, activation and login related cases

5. User login interface

When the user is not activated, the login will inform that it is not activated and needs to be deactivated. When it is activated, the login will be successful when the information is normal. When it is successful, some information of the user will be returned and a token will be added.
The login routes in routes are as follows:

//user_login
router.post('/user_login', userCtrl.user_login);

The login codes in controllers are as follows:

try {
        const user = await findUserAsyc({ 'useremail': user_email });// Verify that the user is registered
        if (!user) {
            respondData.status = 10000;
            respondData. Error = "mailbox is not registered";
            return res.json(respondData);
        }
        const userverify = await findUserVerify(user_email,user_password);// Authentication user
        if(!userverify){
            respondData.status = 10005;
            respondData. Error = "mailbox or password error";
            return res.json(respondData);
        }
        console.log(userverify);
        if(userverify.status === 0){
            respondData.status = 10006;
            respondData. Error = "mailbox is not activated, please activate mailbox";
            return res.json(respondData);
        } else if(userverify.status === 1){
            const tokenexpiraton = 1800;
            const token = require('crypto').randomBytes(16).toString('hex');
            const tokenContent = {
                useremail: userverify.useremail,
                username: userverify.username
            };
            redis.set(token, JSON.stringify(tokenContent));
            redis.expire(token, tokenexpiraton);
            const userBackInfo = {};
            userBackInfo.token = token;
            userBackInfo.useremail = userverify.useremail;
            userBackInfo.username = userverify.username;
            userBackInfo._id = userverify._id;
            respondData.data.push(userBackInfo);
            respondData. MSG = "login succeeded";
            return res.json(respondData);
        }    
    } catch (error) {
        //Error handling
        console.log("controllers/UserController.js/user_regist error -->" + JSON.stringify(error));
        respondData.error = error;
        return res.json(respondDaata);
    }

When login is not activated
node. JS mailbox registration, activation and login related cases
When login is activated
node. JS mailbox registration, activation and login related cases

6. Follow up

At present, only the registration, activation and login interfaces can realize more functions in the follow-up. At the same time, there is no test. In fact, the test can also be added.

Recommended Today

redis day2

persistence mechanism client redis[memory] —–&gt; memory data-data persistence–&gt;disk Redis officially provides two different persistence methods to store data in memory to the hard disk: Snapshot AOF (Append Only File) only appends log files   Snapshot Features:In this way, all data at a certain moment can be written to the hard disk, of course, this is […]