Code design is messy, after finishing the jade template, decided to link login registration function, but found a lot of implementations are too good, first modified the Httpparam get, post, cookie method. Now decide to modify the session, because the session is too unreasonable.
1. The combination of comparative confusion
2. Session and Redis operation together, no independent out
3. The data stored in the session is not clear
4. Expiration is set in session, but it is not necessary because the expiration time has been set in Redis
5. The session expiration time is not updated when the page is toggled
The following is the previous implementation:
/** * @description Create a session for the user * @param {objetc} res * @param {string} ID session on server-side flag * @returns {Newsession.sessio n} */function newsession (Res,serverid) {var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz" ; var sessid = '; for (var i = 0; i < i++) {var num = Math.floor (math.random () * chars.length);//Get a number between 0-39 sessid + = chars.substring (num, num + 1); } lib.redis.exist (sessid, function (EXISTFLG) {if (EXISTFLG) {sessid = new newsession (res); } var dt = new Date (); Dt.setminutes (dt.getminutes () + 30); var session = {sessid:sessid, expires:dt}; SESSIONS[SESSID] = session; Savesession (Sessions[sessid], serverid); Res.setheader (' Set-cookie ', ' sessid= ' + sessid); Res.render (' Home.jade ', {' username ': ServerID}); });}; function Cleansession () {for (Sess in sessions) {if (Sess.expires < Date ()) { Delete Sessions[sess. SESSID]; }}}/** * * @param {Sessions} NewSession object created * @param {type} server flag User ID * @returns {undefined} */function savesession (Session, ID) {session.id = ID; Lib.redis.hmset ("Sessid", {"Sessid": Session. SESSID, "Expires": Session.expires, "username": session.id}); };
Too many unnecessary things, the most uncomfortable for me is that I stored the username in Redis, modified as follows:
Modify a single data Mobgodb read, here has been undefined, do not say nonsense, mainly mixed with the shell call FindOne, the program FindOne through the callback function to obtain results. Modified under:
/** * Find a single data * does not find through the system MongoDB * Change:use FindOne to replace Find method; */ This.findonebyid = function (TableName, Wherejson, callback) { connection (function (mdbconn) { Mdbconn.collection (TableName, function (Err, collection) { if (err) { return; } Collection.findone (Wherejson, function (err, item) { if (item) { Console.log (item); Callback (item); } else { callback (FALSE);}});});};
In the following case, the path of the resource file has changed, such as the following example, I call the Index.jade file, at this time the path to load the CSS into a login/index.css, the previously loaded path is INDEX.CSS, the file is now processed in the login file. Why is it so unreasonable that I don't know why.
Fix it temporarily, modify the route: Take off all the previous, hehe.
var part = Requirepath.split ('/'); Realpath + = Part.pop ();
This.login = function () { Lib.httpParam.POST (req, function (value) { Value.password = Digist.tcrypto ( Value.password); Usermoduleread.checkuser (value, function (Result) { if (result!== false) { lib.session.setSession (res, req, RESULT._ID, function (session) { res.setheader (' Set-cookie ', ' sessid= ' + Session. SESSID); Res.render (' Index.jade ', {' username ': result.username}) ;} else{ res.render (' Login.jade ', {' Error ': "Username or password Wrong"});});};
Login This piece is here: The following is the modified session
/** * * @type @exp; session * @description User login, set the user's session */var Httpparam = require ('./httpparam.js '); var sessions = {};/** * @description get session information in user Header.cookie header * @param {type} res * @param {type} req * @returns {Boolean} failed to return false Successfully returns the current cookie in SESSIONID */var getcookiesession = function (res, req) {var cookie = Httpparam.cookie (req, ' SESSIONID ') ); if (cookie) {var SessionID = cookie; return SessionID; } return false;};/ * * * * @param {type} sessionId "fetch a session from Redis" * @returns {false | session} */var getsession = function (sess Ionid, callback) {lib.redis.exist (sessionId, function (ret) {if (ret) {var session = Lib.hgetall (s Essionid); Callback (session); } callback (FALSE); });};/ * * @description Get the status information of the current session, record the user ID that gets the login to the site * @param {type} res * @param {type} req * @returns {newsession.session|s essions|session} */exports.sessionstatus = function (res, req) {var SessionID = gEtcookiesession (res, req); Lib.redis.exist (SessionID, function (EXISTFLG) {if (EXISTFLG) {var Sessionjson = Lib.redis.hgetall (ses Sionid); if (Sessionjson.expires < Date ()) {Lib.redis.del (SessionID); Global.userid = 0; } else {var dt = new Date (); Dt.setminutes (dt.getminutes + 30); sessionjson.expires = DT; Lib.redis.hset (Sesionid, Sessionjson); Global.userid = Sessionjson.userid}});} /** * @description When the user logs on or register, set the user's session information * @param {type} res * @param {type} req * @returns {Newsession.sessi on|sessions|session} */exports.setsession = function (res, req, UserID, callback) {newsession (res, userid, function (s ession) {savesession (Session, function (session) {callback (session); }); });};/ * * @description Create a session for the user * @param {objetc} res * @param {StrinG} ID session on server-side flag * @returns {JSON} */function newsession (res, userId, callback) {var chars = "0123456789ABCDEFGH IJKLMNOPQRSTUVWXYZABCDEFGHIGKLMNOPQRSTUVWXYZ "; var sessid = '; for (var i = 0; i < i++) {var num = Math.floor (math.random () * chars.length);//Get a number between 0-39 sessid + = chars.substring (num, num + 1); } lib.redis.exist (sessid, function (EXISTFLG) {if (EXISTFLG) {sessid = new NewSession (res, userId); } var dt = new Date (); Dt.setminutes (dt.getminutes () + 30); var session = {Sessid:sessid, expires:dt, Userid:userid}; Callback (session); });}; function Delsession (sessionId) {lib.redis.exist (sessionId, function (ret) {if (ret) {Lib.redis.del (SESSIONID); } });} /** * Save the session to Redis * @param {sessions} NewSession created Object * @param {type} server flag User ID * @returns {undefined} */fu Nction Savesession (Session,Callback) {Lib.redis.hmset (session). Sessid, {"Expires": Session.expires, "UserId": Session.userid}); Callback (session);};/ * * If user has logined */exports.islogin = function (res, req, callback) {//if sessid in cookie existed var Sessio NId = Getcookiesession (res, req); if (sessionId = = = False) {return false; } lib.redis.exist (SessionId, function (ret) {if (ret) {callback (SESSIONID); } callback (FALSE); });};
node. js with Redis Implementation Session modification complete (2)