Im trying to learn Node.js without using any third party modules or frameworks. I'm getting to the point where I got to figure out how to give session ids to users who login...
So far I know I can set the session id by writing it in the headers, setting the cookies:
writeHead(200, {'set-cookie':'Math.random() ' } );
and then I can retrieve the session id and later compare it to the database.
request.headers.cookie(request.url);
But how do I GENERATE the session ID value? I am new to programming. The first thing I thought of was using Javascript's Math.random(); and using that value to set the cookie ( session id ). In my mind it feels stupid but that is how far I can think.
How am I suppose to generate the session id using Node.js, no third party modules, barebones please!
The SessionID value is randomly generated by ASP.NET and stored in a non-expiring session cookie in the browser. The SessionID value is then sent in a cookie with each request to the ASP.NET application.
An HTTP session's identifier is a unique string which is created and maintained by the server. Returns the last time the client sent a request carrying the assigned session identifier (or -1 if its a new session) in milliseconds since January 1, 1970, 00:00:00 GMT.
Session ID is created according to php. ini settings. It is important to use the same user ID of your web server for GC task script. Otherwise, you may have permission problems especially with files save handler.
Note: You should probably use a session manager for whatever framework you go with.. be it connect, express, koa or any number of others.
This will give you a UUID version 4 (random) using crypto.randomBytes
.
var crypto = require('crypto');
module.exports = genUuid;
function genUuid(callback) {
if (typeof(callback) !== 'function') {
return uuidFromBytes(crypto.randomBytes(16));
}
crypto.randomBytes(16, function(err, rnd) {
if (err) return callback(err);
callback(null, uuidFromBytes(rnd));
});
}
function uuidFromBytes(rnd) {
rnd[6] = (rnd[6] & 0x0f) | 0x40;
rnd[8] = (rnd[8] & 0x3f) | 0x80;
rnd = rnd.toString('hex').match(/(.{8})(.{4})(.{4})(.{4})(.{12})/);
rnd.shift();
return rnd.join('-');
}
You could also use the UUID module from npm. The crypto package is not an in-browser option, though you could use Browserify's crypto shim.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With