Modify the Index.js as follows:
varExpress = require (' Express ');varRouter =Express. Router ();varCrypto=require (' Crypto ');varUser=require (".. /models/user.js ");/*GET home page.*/Router.get (‘/‘,function(req, res, next) {Res.render (' Index ', {title: ' Home ', Error:req.flash ("error"). ToString (), Success:req.flash ("Success" ). toString (), user:req.session.user}); Router.get ( '/reg ' , checknotlogin); Router.get ('/reg ',function(Req,res,next) {Res.render (' Reg ', {title: ' Register ' });}); Router.post ( '/reg ' , checknotlogin); Router.post ('/reg ',function(req,res,next) {varName=req.body.name, Password=Req.body.password, Repassword=Req.body.repassword; if(repassword!==password) {Req.flash ("Error", "password inconsistent two times"); returnRes.redirect ("/reg"); } varMd5=crypto.createhash (' MD5 '); Password=md5.update (Req.body.password). Digest (' Hex ')); varNewuser=NewUser ({name:req.body.name, Password:password, email:req.body.email}); User.get (Newuser.name,function(err,user) {if(user) {Req.flash (' Error ', ' User name already exists '); returnRes.redirect ("/reg"); } newuser.save (function(err,user) {if(Err) {Req.flash ("Error", err); returnRes.redirect ("/reg"); } Req.session.user=user; Req.flash ("Success", "registered successfully"); Res.redirect ("/"); }); });}); Router.get ( '/login ' , checknotlogin); Router.get ('/login ',function(Req,res,next) {Res.render (' Login ', {title: ' Login ' });}); Router.post ( '/login ' , checknotlogin); Router.post ('/login ',function(req,res,next) {varMd5=crypto.createhash ("MD5"); Password=md5.update (Req.body.password). Digest (' Hex ')); User.get (Req.body.name,function(err,user) {if(!user) {Req.flash (' Error ', ' User not present '); returnRes.redirect ("/login"); } if(user.password!==password) {Req.flash ("Error", "Password Wrong"); returnRes.redirect ("/login"); } req.flash ("User", req.session.user=user); Req.flash (' Success ', ' login successful '); Res.redirect ("/"); })}); Router.get ( '/logout ' , checklogin); Router.get ("/logout",function(req,res) {Req.flash ("User", req.session.user=NULL); Req.flash ("Success", "Log Out Success"); Res.redirect ("/");}); Router.get ( '/post ' , checklogin); Router.get ('/post ',function(Req,res,next) {Res.render (' Post ', {title: ' Publish ' });}); Router.post ( '/post ' , checklogin); Router.post ('/post ',function(Req,res,next) {});function Checklogin (req,res,next) {if (!req.session.user) {Req.flash ("error", "not logged in"); Return Res.redirect ("/login"); } next ();} function Checknotlogin (req,res,next) {if (Req.session.user) {Req.flash ("error", "Logged in"); Return Res.redirect ("Back"); } next ();} Module.exports= Router;
Use Express+mongodb to build multiplayer blog learning (5) Permission control