Node JS combat: Registered login form with database and encryption

Source: Internet
Author: User
Tags mongoclient



Demo



Registration effect:






Landing effect:












Database:






Database operations



Db.js


/ / This module encapsulates all the common operations on the database
Var MongoClient = require(‘mongodb‘).MongoClient;
Var settings = require("../settings.js");
/ / Regardless of the operation of the database, are the first to connect to the database, so we can connect to the database
/ / Encapsulation becomes an internal function
Function _connectDB(callback) {
    Var url = settings.dburl; //from the settings file, all database addresses
    //Connect to the database
    MongoClient.connect(url, function (err, db) {
        If (err) {
            Callback(err, null);
            Return;
        }
        Callback(err, db);
    });
}

/ / Insert data
exports.insertOne = function (collectionName, json, callback) {
    _connectDB(function (err, db) {
        Db.collection(collectionName).insertOne(json, function (err, result) {
            Callback(err, result);
            Db.close (); / / close the database
        })
    })
};

// Find the data and find all the data. Args is an object {"pageamount":10,"page":10}
Exports.find = function (collectionName, json, C, D) {
    Var result = []; // result array
    If (arguments.length == 3) {
        // Then the parameter C is the callback, and the parameter D is not passed.
        Var callback = C;
        Var skipnumber = 0;
        //number limit
        Var limit = 0;
    } else if (arguments.length == 4) {
        Var callback = D;
        Var args = C;
        //The number of bars that should be omitted
        Var skipnumber = args.pageamount * args.page || 0;
        //number limit
        Var limit = args.pageamount || 0;
        //Sort by
        Var sort = args.sort || {};
    } else {
        Throw new Error("The number of arguments to the find function must be 3, or 4.");
        Return;
    }

    / / Connect to the database, find all after the connection
    _connectDB(function (err, db) {
        Var cursor = db.collection(collectionName).find(json).skip(skipnumber).limit(limit).sort(sort);
        Cursor.each(function (err, doc) {
            If (err) {
                Callback(err, null);
                Db.close (); / / close the database
                Return;
            }
            If (doc != null) {
                Result.push(doc); //put the result array
            } else {
                //The traversal is over, there are no more documents.
                Callback(null, result);
                Db.close (); / / close the database
            }
        });
    });
}

//delete
exports.deleteMany = function (collectionName, json, callback) {
    _connectDB(function (err, db) {
        //delete
        Db.collection(collectionName).deleteMany(
            Json,
            Function (err, results) {
                Callback(err, results);
                Db.close (); / / close the database
            }
        );
    });
}

//modify
exports.updateMany = function (collectionName, json1, json2, callback) {
    _connectDB(function (err, db) {
        Db.collection(collectionName).updateMany(
            Json1,
            Json2,
            Function (err, results) {
                Callback(err, results);
                Db.close();
            });
    })
}

exports.getAllCount = function (collectionName,callback) {
    _connectDB(function (err, db) {
        Db.collection(collectionName).count({}).then(function(count) {
            Callback(count);
            Db.close();
        });
    })
}


Password encryption:


 
var crypto = require("crypto");
module.exports = function(mingma){ var md5 = crypto.createHash(‘md5‘); var password = md5.update(mingma).digest(‘base64‘); return password;
}


Template:



Login.ejs


<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>Please login</h1>
    <div>
        <form action="" method="post">
            <p>
                Login name: <input type="text" id="dengluming"/>
            </p>
            <p>
                Password: <input type="password" id="mima"/>
            </p>
            <p>
                <input id="denglu" type="button" value="Login"/>
            </p>
        </form>
    </div>

    <script type="text/javascript" src="/jquery-1.11.3.min.js"></script>
    <script type="text/javascript">
        / / Use ajax to submit the form
        $("#denglu").click(function(){
            $.post("/dologin",{
                "dengluming" : $("#dengluming").val(),
                "mima" : $("#mima").val()
            },function(result){
                If(result == "1"){
                    Alert ("Login successful");
                }else if(result == "-2"){
                    Alert ("There is no such registered user");
                }else if(result == "-1"){
                    Alert ("Password is incorrect");
                }
            })
        });
    </script>
</body>
</html>


regist.ejs


<!doctype html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title></title>
</head>
<body>
     <div>
         <p>
             Login name: <input type="text" name="dengluming" id="dengluming"/>
         </p>
         <p>
             Password: <input type="password" name="mima" id="mima"/>
         </p>
         <p>
             <input id="zhuce" type="button" value="Register"/>
         </p>
     </div>

     <script type="text/javascript" src="/jquery-1.11.3.min.js"></script>
     <script type="text/javascript">
         / / Use ajax to submit the form
         $("#zhuce").click(function(){
             $.get("/doregist",{
                 "dengluming" : $("#dengluming").val(),
                 "mima" : $("#mima").val()
             },function(result){
                 If(result == "1"){
                     Alert ("registration succeeded");
                 }else{
                     Alert ("registration failed");
                 }
             })
         });
     </script>
</body>
</html>


sign up:


Var express = require("express");
Var app = express();
Var formidable = require(‘formidable‘);
Var db = require("./model/db.js");

Var md5 = require("./model/md5.js");

App.set("view engine","ejs");

App.use(express.static("./public"));

//registration page
App.get("/regist",function(res,res,next){
    Res.render("regist");
});

//login page
App.get("/login",function(res,res,next){
    Res.render("login");
});

//Execute registration
App.get("/doregist",function(req,res,next){
    Var dengluming = req.query.dengluming;
    Var mima = req.query.mima;
    //encryption
    Mima = md5(md5(mima).substr(4,7) + md5(mima));

    / / Save the username and password in the database
    db.insertOne("users",{
        "dengluming" : dengluming,
        "mima" : mima
    },function(err,result){
        If(err){
            Res.send("-1");
            Return;
        }
        Res.send("1");
    })
});

App.post("/dologin",function(req,res,next){
    Var form = new formidable.IncomingForm();

    Form.parse(req, function(err, fields, files) {
        Var dengluming = fields.dengluming;
        Var mima = fields.mima;
        Mima = md5(md5(mima).substr(4,7) + md5(mima));

        / / Retrieve the database, retrieve the database by login name, check whether the password matches
        Db.find("users",{"dengluming":dengluming},function(err,result){
           If(result.length == 0){
               Res.send("-2"); //-2 no such person
               Return;
           }
            Var shujukuzhongdemima = result[0].mima;
            // To perform the same encryption operation on the password entered by the user this time. Then with
            / / Database password comparison
            If(mima == shujukuzhongdemima){
                Res.send("1"); //Success
            }else{
                Res.send("-1"); //Password does not match
            }
        });
    });

    Return;
});

App.listen(3000);


Database address:

Settings.js

module.exports = {
    "dburl" : "mongodb://localhost:27017/day7"
}


 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.