server.js
2.6 KB
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
99
100
101
'use strict';
// Mock server for serving Oauth2 tokens
var http = require('http');
var crypto = require('crypto');
var querystring = require('querystring');
module.exports = function(options) {
return new OAuthServer(options);
};
function OAuthServer(options) {
this.options = options || {};
this.users = {};
this.tokens = {};
this.options.port = Number(this.options.port) || 3080;
this.options.expiresIn = Number(this.options.expiresIn) || 3600;
}
OAuthServer.prototype.addUser = function(username, refreshToken) {
var user = {
username: username,
refreshToken: refreshToken || crypto.randomBytes(10).toString('base64')
};
this.users[username] = user;
this.tokens[user.refreshToken] = username;
return this.generateAccessToken(user.refreshToken);
};
OAuthServer.prototype.generateAccessToken = function(refreshToken) {
var username = this.tokens[refreshToken];
var accessToken = crypto.randomBytes(10).toString('base64');
if (!username) {
return {
error: 'Invalid refresh token'
};
}
this.users[username].accessToken = accessToken;
this.users[username].expiresIn = Date.now + this.options.expiresIn * 1000;
if (this.options.onUpdate) {
this.options.onUpdate(username, accessToken);
}
return {
access_token: accessToken,
expires_in: this.options.expiresIn,
token_type: 'Bearer'
};
};
OAuthServer.prototype.validateAccessToken = function(username, accessToken) {
if (!this.users[username] ||
this.users[username].accessToken !== accessToken ||
this.users[username].expiresIn < Date.now()) {
return false;
} else {
return true;
}
};
OAuthServer.prototype.start = function(callback) {
this.server = http.createServer((function(req, res) {
var data = [];
var datalen = 0;
req.on('data', function(chunk) {
if (!chunk || !chunk.length) {
return;
}
data.push(chunk);
datalen += chunk.length;
});
req.on('end', (function() {
var query = querystring.parse(Buffer.concat(data, datalen).toString()),
response = this.generateAccessToken(query.refresh_token);
res.writeHead(!response.error ? 200 : 401, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(response));
}).bind(this));
}).bind(this));
this.server.listen(this.options.port, callback);
};
OAuthServer.prototype.stop = function(callback) {
this.server.close(callback);
};