How do I generate a session ID in Node.js?
Asked Answered
P

1

7

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!

Peridotite answered 14/10, 2014 at 1:27 Comment(1)
It's a good question... just beware that there are strong security implications of how you handle session IDs in cookies. Whatever you do, don't implement what you build in production use. There is a ton of well-tested off-the-shelf code you can use. Now, you can generate your session ID however you want. This isn't a Node.js question really. It's a best practice and JavaScript question.Skutchan
T
5

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.

Tacho answered 14/10, 2014 at 2:40 Comment(2)
can you tell me what concept you used in the uuidFromBytes function?Merchant
UUID and v4 have requirements that certain bytes contain certain values. it receives the bytes for the full result, tweaks to ensure the reserved field values, and assembles the string... it matches the blocks of the converted hex result, and from there joins the result together. The shift removes the full result from the parts.Tacho

© 2022 - 2024 — McMap. All rights reserved.