Node JS combat: Registered login form with database and encryption

Source: Internet
Author: User

Tags: input throw htm col CTI ports Create let use

Demo

Registration effect:

Landing effect:

Database:

Database operations

Db.js

This module encapsulates all the common operations of the database var mongoclient = require (' MongoDB '). Mongoclient;var settings = require ("..   /settings.js ");//Regardless of database operation, are connected to the database, so we can connect the database//encapsulated into the internal function functions _connectdb (callback) {var url = settings.dburl; From the settings file, both the database address//Connection database Mongoclient.connect (URL, function (err, db) {if (err) {Callback (ER            R, NULL);        Return    } callback (err, DB); });} Insert Data Exports.insertone = function (CollectionName, JSON, callback) {_connectdb (function (err, db) {Db.collect            Ion (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": Ten, "page": 10}exports.find = function (CollectionName, JSON, C, D) {var result = [];        Result array if (arguments.length = = 3) {//Then parameter C is callback, 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; 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 and find all _CONNECTDB (err, db) {var cursor = db.collection (collectionname) after connection. FIND (JSON). Skip        (Skipnumber). Limit (limit). sort (sort);                Cursor.each (err, doc) {if (err) {callback (err, NULL); Db.close ();            Close the database return;   } if (Doc! = null) {Result.push (doc);                Put in the result array} else {//traversal end, no more documents callback (null, result); Db.close ();    Close Database}}); });}        Delete Exports.deletemany = function (CollectionName, JSON, callback) {_connectdb (function (err, db) {//delete Db.collection (collectionname). Deletemany (JSON, function (err, results) {callback (Err, result                s); Db.close ();    Close database}); });} Modify Exports.updatemany = function (CollectionName, Json1, Json2, callback) {_connectdb (the 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 (coll            Ectionname). Count ({}). Then (function (count) {callback (count);        Db.close ();    }); })}

Password encryption:

var crypto = require ("crypto"= 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 AC tion=""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">//submit a form with Ajax$("#denglu"). Click (function () {$.post ("/dologin",{                "dengluming": $("#dengluming"). Val (),"Mima": $("#mima"). Val ()},function (result) {if(Result = ="1") {alert ("Landing Success"); }Else if(Result = ="-2") {alert ("without this registered user"); }Else if(Result = ="-1") {alert ("The password is not correct");    }            })        }); </script></body></html>

Regist.ejs

<!doctype html><html lang= "en" ><head> <meta charset= "UTF-8" > <title></title>&lt ;/head><body> <div> <p> Login name: <input type= "text" name= "dengluming" id= "Denglum ing "/> </p> <p> Password: <input type=" password "name=" Mima "id=" Mima "/> &L    t;/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 ("registered successfully");                }else{alert ("Registration failed");    }            })        }); </sCript></body></html> 

Login Registration:

var express = require ("Express"), var app = Express (), var formidable = require (' formidable '); var db = require ("./MODEL/DB.J S "), 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");}); /landing 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 username and password to 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, and see if the password matches db.find ("users", {"dengluming":d engluming},function (Err,result) {if (Result.leng  th = = 0) {res.send ("-2");           -2 No this person return;            } var Shujukuzhongdemima = Result[0].mima; For the user to enter the password this time, the same encryption operation.  Then the password in the//database is compared to if (Mima = = Shujukuzhongdemima) {res.send ("1");    Successful}else{res.send ("1");//Password Mismatch}});    }); return;}); App.listen (3000);

Database address:

Settings.js

Module.exports = {
"Dburl": "Mongodb://localhost:27017/day7"
}





Node JS combat: Registered login form with database and encryption

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.

Tags Index: