-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (58 loc) · 2.12 KB
/
index.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
//Import dependencies
var url = require('url');
var jwt = require('jwt-simple');
//Authentication
var config = { id: '', secret: '', url: 'https://account.mgviz.org' };
//Set the client configuration
module.exports.set = function(obj)
{
//Check for undefined object
if(typeof obj !== 'object'){ return; }
//Extend the configuration object
config = Object.assign(config, obj);
//Parse the client id
if(typeof config.id === 'string'){ config.id = config.id.trim(); }
//Parse the client secret key
if(typeof config.secret === 'string'){ config.secret = config.secret.trim(); }
};
//Build the authentication url
module.exports.get_url = function(cb)
{
//Check the client id
if(typeof config.id !== 'string' || config.id === ''){ return cb(new Error('No client ID provided')); }
//Check the client secret key
if(typeof config.secret !== 'string' || config.secret === ''){ return cb(new Error('No client secret key provided')); }
//Build the authorization url
var auth_url = url.resolve(config.url, '/authorize?client=' + config.id);
//Return the url
return cb(null, auth_url);
};
//Verify the token
module.exports.verify_token = function(token, cb)
{
//Check the client id
if(typeof config.id !== 'string' || config.id === ''){ return cb(new Error('No client ID provided')); }
//Check the client secret key
if(typeof config.secret !== 'string' || config.secret === ''){ return cb(new Error('No client secret key provided')); }
//Decode the json
try
{
//Decode the token
var obj = jwt.decode(token, config.secret);
//Check the creation and the expiration time
if(typeof obj.iat !== 'number' || typeof obj.exp !== 'number'){ return cb(new Error('Invalid token'), {}); }
//Get the actual time in seconds
var time_now = new Date().getTime() / 1000;
//Check for a valid token
if(time_now < obj.iat){ return cb(new Error('Invalid token'), {}); }
//check for an expired token
if(obj.exp < time_now){ return cb(new Error('Expired token'), {}); }
//Do the callback
return cb(null, obj);
}
catch(error)
{
//Return with the error
return cb(error, {});
}
};