Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How it is possible to generate session id in node.js? [duplicate]

I would like to work with sessions on low level. How is it possible to generate session id in node.js?

like image 863
avasin Avatar asked Aug 06 '13 11:08

avasin


1 Answers

It is not clear what you are trying to achieve, but... a session ID is just an ID! You generate it however you want. There are no requirements except for uniqueness. It is a good idea though to make it secure. For example this function may be your session id generator:

var crypto = require('crypto');

var generate_key = function() {
    // 16 bytes is likely to be more than enough,
    // but you may tweak it to your needs
    return crypto.randomBytes(16).toString('base64');
};

You call generate_key() and you check whether it exists in a database. If it does you call it again and so on and so on.

EDIT: Let me address comments:

  1. Originally I had Math.random() here and there were some concerns that this is not cryptographically secure. While it is true, I don't see OP asking for cryptographically secure solution. For all we know he may not need it, after all we don't know what kind of sessions he is dealing with. Ultimately I've decided to change it, cause crypto solution is safer and (most of the time) it doesn't have any drawback.
  2. Uuid is an acceptable alternative. I personally prefer uuid4 since it doesn't leak information but it doesn't really matter.
  3. The amount of computation needed to generate any sort of id is unlikely to matter and it will be dominated by a database communication most of the time (if there is any). Unless you are dealing with pbkdf2 kind of algorithms. I wouldn't use that. But if you are then you probably have your reasons.
like image 157
freakish Avatar answered Oct 12 '22 13:10

freakish