-
Notifications
You must be signed in to change notification settings - Fork 0
/
microservice-github-oauth.js
217 lines (199 loc) · 5.5 KB
/
microservice-github-oauth.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* Profile Stats MicroService.
*/
'use strict';
const framework = '@microservice-framework';
const Cluster = require(framework + '/microservice-cluster');
const Microservice = require(framework + '/microservice');
const MicroserviceRouterRegister = require(framework + '/microservice-router-register').register;
const clientViaRouter = require(framework + '/microservice-router-register').clientViaRouter;
const debugF = require('debug');
const https = require('https');
const fs = require('fs');
const url = require('url');
var debug = {
log: debugF('github-oauth:log'),
debug: debugF('github-oauth:debug')
};
require('dotenv').config();
let permissionsPath = './permissions.json';
if (process.env.PERMISSION_PATH) {
permissionsPath = process.env.PERMISSION_PATH;
}
var mservice = new Microservice({
mongoUrl: '',
mongoTable: '',
secureKey: process.env.SECURE_KEY,
schema: process.env.SCHEMA
});
var mControlCluster = new Cluster({
pid: process.env.PIDFILE,
port: process.env.PORT,
hostname: process.env.HOSTNAME,
count: process.env.WORKERS,
callbacks: {
init: microserviceGithubOAuthINIT,
POST: microserviceGithubOAuthPOST,
OPTIONS: mservice.options
}
});
/**
* Init Handler.
*/
function microserviceGithubOAuthINIT(cluster, worker, address) {
if (worker.id == 1) {
var mserviceRegister = new MicroserviceRouterRegister({
server: {
url: process.env.ROUTER_URL,
secureKey: process.env.ROUTER_SECRET,
period: process.env.ROUTER_PERIOD,
},
route: {
path: [process.env.SELF_PATH],
url: process.env.SELF_URL,
secureKey: process.env.SECURE_KEY,
},
cluster: cluster
});
}
}
/**
* POST handler.
*/
function microserviceGithubOAuthPOST(jsonData, requestDetails, callback) {
try {
// Validate jsonData.code for XSS
mservice.validateJson(jsonData);
} catch (e) {
return callback(e, null);
}
let tokenUrl = process.env.GITHUB_URL
+ '?code=' + jsonData.code
+ '&client_id=' + process.env.CLIENT_ID
+ '&client_secret=' + process.env.CLIENT_SECRET;
simpleRequest(tokenUrl, function(err, answer){
if (err) {
return callback(err);
}
if (!answer.access_token) {
return callback(new Error('Failed to get access_token.'));
}
let apiURL = process.env.GITHUB_API_URL;
if (apiURL[apiURL.length -1 ] != '/') {
apiURL = apiURL + '/'
}
apiURL = apiURL + 'user?access_token=' + answer.access_token;
// Get user info by token
simpleRequest(apiURL, function(err, apiAnswer){
if (err) {
return callback(err);
}
if (!apiAnswer.login) {
return callback(new Error('Failed to get login.'));
}
getScope(function(err, roleJSON) {
if (err) {
return callback(err);
}
// scope it and return access token
let scopeRequest = {
credentials: {
login: apiAnswer.login,
githubToken: answer.access_token
},
scope: roleJSON
}
if (process.env.DEFAULT_TTL) {
scopeRequest.ttl = parseInt(process.env.DEFAULT_TTL);
}
clientViaRouter('auth', function(err, authServer) {
if (err) {
return callback(err);
}
authServer.post(scopeRequest, function(err, authAnswer) {
if (err) {
debug.debug('authServer.post err %O', err);
debug.log('authServer.post failed with error.');
return callback(err);
}
let handlerAnswer = {
code: 200,
answer: {
accessToken: authAnswer.accessToken,
expireAt: authAnswer.expireAt,
githubToken: answer.access_token
}
}
return callback(err, handlerAnswer);
});
});
})
})
})
}
/**
* Read scope from filesystem.
*/
function getScope(callback) {
let roleJSON;
fs.readFile(permissionsPath, function(err, data){
if (err) {
return callback(err);
}
try {
roleJSON = JSON.parse(data);
callback(null, roleJSON);
} catch (e) {
return callback(new Error('Failed to load role permissions'));
}
})
}
/**
* Wrapper around https.get.
*/
function simpleRequest(requestUrl, callback) {
const parsedURL = url.parse(requestUrl);
let path = '';
if(parsedURL.pathname) {
path= path + parsedURL.pathname;
}
if(parsedURL.search) {
path= path + parsedURL.search;
}
let options = {
method: 'GET',
host: parsedURL.host,
port: 443,
path: path,
headers: {
Accept: 'application/json',
'User-Agent': process.env.mfw_package_name + '@' + process.env.mfw_package_version
}
};
debug.debug("Options %O parsedURL %O ", options, parsedURL);
const req = https.request(options, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
try {
debug.debug("Data: %s", data);
let answer = JSON.parse(data);
if(answer.error) {
return callback(new Error(answer.error));
}
callback(null, answer);
} catch (e) {
debug.debug("Parse error: %s, %s, %O", url, data, e);
debug.log("request.error Failed to parse respond: %s", e);
callback(new Error('Failed to parse respond.'));
}
});
}).on("error", (err) => {
debug.debug("Error: %O", err);
debug.log("request.error: %s", err.message);
callback(err);
});
req.end();
}