Login
Modify Index.ejs
<%-include header%> <% if (locals.error) {%> <span><%= locals.error%></span > <%}%> <form method= "POST" > User name:<input type= "text" name= "name"/> <br/> Password:<input type= "password" name= "password"/><br/> <input type= "Submit" value= "Login"/> </form><%-include footer%>
Modify Index.js
Router.post ('/login ',function(req,res,next) { var md5=crypto.createhash ("MD5"); Password=md5.update (Req.body.password). Digest (' Hex '); Console.log (req.body.name); User.get (Req.body.name,function (err,user) { if (!user) { req.flash (' Error ', "User does not exist"); Return Res.redirect ("/login"); } Console.log (User.password,password); if (User.password!==password) { Req.flash ("Error", "Bad password"); Return Res.redirect ("/login"); } Req.session.user=user; Req.flash (' success ', "Login Successful"); Res.redirect ("/"); })});
Log out
New in Index.js:
Router.get ("/logout",function(req,res) { Req.session.user=null; Req.flash ("Success", "logout Success"); Res.redirect ("/");});
Now login in the browser after entering: localhost:3000/logout
Modify a template
Login.ejs Index.ejs and Req.ejs.
<% if (locals.xxx) {%>
<span><%= locals.xxx%></span>
<%}%>
This kind of code, remove them.
Modify the Header.ejs as follows:
<! DOCTYPE html><% if (locals.user) {%> <span><a title= "published" Href= "/post" >post</a></span> & Lt;span><a title= "Logout" href= "/logout" >logout</a></span> <%}else{%> <span>& Lt;a title= "Login" href= "/login" >login</a></span> <span><a title= "register" href= "/reg" >register& Lt;/a></span> <%}%></nav> <article><% if (locals.error) {%> <span><%= locals.error%></span> <%}%> <% if (locals.success) {%> <span><%= locals.success%></span> <%}%> ;
Modify Index.js
Router.post ('/login ',function(req,res,next) {varMd5=crypto.createhash ("MD5"); Password=md5.update (Req.body.password). Digest (' Hex ')); Console.log (Req.body.name); User.get (Req.body.name,function(err,user) {if(!user) {Req.flash (' Error ', ' User not present '); returnRes.redirect ("/login"); } console.log (User.password,password); 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",function(req,res) { Req.flash ( "User", Req.session.user=null); Req.flash ("Success", "Log Out Success"); Res.redirect ("/");});
Modify App.js
App.use (function(req, res, next) { = Req.flash (' ERROR '). toString (); = Req.flash (' Success '). toString (); Res.locals.user =req.flash ("user"). toString (); Next ();});
Use Express+mongodb to build multiplayer blog learning (4) Login and Logout