-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenize.js
98 lines (85 loc) · 2.65 KB
/
tokenize.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var crypto = require('crypto');
// TODO: the vector is used to encrypt the server key & the rest of the data
var crypto_vector = 'qwertyuiop[]';
// TODO: key will be encrypted and sended to the client
var server_key = 'unacadenamuyperoquemuylargo';
/**
* This method create a hash from a text
* @param text {String} string to be encoded
* @param method {String} hashing method to be used
* @return {string}
*/
function hashify(text, method){
//TODO: here check is method is a know hashing method
return crypto.createHash(method).update(text + server_key).digest('hex');
}
/**
* this take a json session object encryot it
* and send it to the user, the token itself contains
* all the information required
* {userId, created, forever, etc[object]}
* @param sessionObj json session data to be included in the jwt
* @return {String}
*/
var tokenize = function(sessionObj){
//TODO: implement here
if(! typeof(sessionObj) == 'object'){
throw Error('sessionObj must be an object');
}
var header = {
'algo': 'sha256',
'type': 'jwt',
'created': Date.now()
};
// convierrto los objetos json en cadenas
var jheader = JSON.stringify(header);
var jdata = JSON.stringify(sessionObj);
//codifico los datos con algoritmo base64
var subkey = new Buffer(jheader).toString('base64')+'.'+new Buffer(jdata).toString('base64');
var signature = hashify(subkey, 'sha256');
return subkey + '.' + signature;
};
/**
* this takes one token key and split it
* @param token {string} raw token string to be processed
* @return array || null
*/
function split(token){
//TODO: implement here
var subelements = token.split('.');
if(subelements.length !== 3){
return null; // this token is not valid
}
return subelements;
};
/**
* Check if a token is valid
* @param token raw jwt to be validate
* @return {Object || null}
*/
var validate = function(token){
//TODO: implement here
if(!'string' === typeof token){
throw Error('The token is not a string');
}
var subitems = split(token);
if(subitems === null){
throw Error('The token is not valid.');
}
var subheader = subitems[0],
subdata = subitems[1],
signature = subitems[2]
;
// antes que nada
// compruebo que la firma del token sea valida,
// para evitar tokens manipulados
if (signature !== hashify(subheader+'.'+subdata, 'sha256')){
console.log('Que no cojones...');
throw Error('Token signature is not valid');
}
jheader = new Buffer(subheader, 'base64').toString('ascii');
jdata = new Buffer(subdata, 'base64').toString('ascii');
return JSON.parse(jdata);
};
exports.tokenize = tokenize;
exports.validate = validate;