Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 778
user3658794 Avatar asked Oct 14 '14 01:10

user3658794


People also ask

How is session ID generated?

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.

Who creates the session ID?

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.

Where is session ID created?

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.


1 Answers

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.

like image 106
Tracker1 Avatar answered Sep 18 '22 23:09

Tracker1