-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathindex.js
307 lines (272 loc) · 7.99 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
const routilCookie = require('routil-cookie');
const url = require('url');
const async = require('async');
const cookieSign = require('cookie-signature');
const deepcopy = require('deepcopy');
const rrs = require('request-retry-stream');
const getCookie = routilCookie.getCookie;
const setCookie = routilCookie.setCookie;
const cookieName = 'gh_uname';
var redirect = function (url, response) {
response.statusCode = 302;
response.setHeader('Location', url);
response.end();
};
var toFunction = function (str) {
return function () {
return str;
};
};
var defaultRandomSecret = Math.random().toString();
var ghSecretState = Math.random().toString();
module.exports = function (clientId, clientSecret, config) {
// We don't want to accidentally mutate the object we were passed.
config = deepcopy(config);
// GitHub enforces lowercase names for organizations and teams.
// The checks later on are simplified by normalizing here.
if (config.organization) {
config.organization = config.organization.toLowerCase();
}
if (config.team) {
config.team = config.team.toLowerCase();
}
var scope = ((config.team || config.organization) && !config.credentials) ? 'user' : 'public';
var secret = config.secret || defaultRandomSecret;
var userAgent = config.ua || 'github-auth';
var redirectUri = config.redirectUri || '';
var accessToken;
if (typeof redirectUri !== 'function') redirectUri = toFunction(redirectUri);
var getRequest = function (url, forceOauth, cb) {
if (typeof forceOauth === 'function') {
cb = forceOauth;
forceOauth = false;
}
if (config.credentials && !forceOauth) {
rrs.get({
url,
headers: {
'User-Agent': userAgent
},
auth: {
user: config.credentials.user,
pass: config.credentials.pass
},
timeout: 10000
}, cb);
} else {
rrs.get({
url,
headers: {
'User-Agent': userAgent,
Authorization: 'token ' +accessToken
},
timeout: 10000
}, cb);
}
};
var getUser = function (callback) {
getRequest('https://api.github.com/user', true, function (err, res, body) {
if (err) return callback(err);
var json;
try {
json = JSON.parse(body);
}
catch (e) {
return callback(new Error(body), null);
}
if (typeof json.login !== 'string' || json.login === '') {
return callback(new Error(`GitHub User has no login, ${body}`), null);
}
callback(null, json.login);
});
};
var getTeamId = function (cb) {
getRequest('https://api.github.com/orgs/' + config.organization + '/teams', function (err, res, body) {
if (err) return cb(err);
var teams;
try {
teams = JSON.parse(body);
}
catch (e) {
return cb(new Error(body), null);
}
var teamId = teams.filter(function (x) {
return x.name === config.team;
})[0].id;
cb(null, teamId);
});
};
var isInTeam = function (ghusr, callback) {
if (!config.organization) return callback(new Error('The organization is required to validate the team.'));
if (!config.team) return callback(new Error('The team is required.'));
if (config.credentials) {
getTeamId(function (err, tid) {
if (err) return callback(err);
getUsersOnTeam(tid, function (err, users) {
if (err) return callback(err);
callback(null, users.indexOf(ghusr) !== -1);
});
});
} else {
rrs.get({
url: 'https://api.github.com/user/teams?access_token=' + accessToken,
headers: {
'User-Agent': userAgent
},
timeout: 10000
}, function (err, res, body) {
if (err) return callback(err);
var json;
try {
json = JSON.parse(body);
}
catch (e) {
return callback(new Error(body), null);
}
if (!Array.isArray(json)) return callback(null, false);
var teamNames = json.map(function (obj) {
return obj.slug;
});
var orgLogins = json.map(function (obj) {
return obj.organization.login;
});
var authorized = teamNames.indexOf(config.team) !== -1 && orgLogins.indexOf(config.organization) !== -1;
callback(null, authorized);
});
}
};
var isInOrganization = function (callback) {
getRequest('https://api.github.com/user/orgs', function (err, res, body) {
if (err) return callback(err);
var json;
try {
json = JSON.parse(body);
}
catch (e) {
return callback(new Error(body), null);
}
if (!Array.isArray(json)) return callback(null, false);
var orgLogins = json.map(function (obj) {
return obj.login;
});
var authorized = orgLogins.indexOf(config.organization) !== -1;
callback(null, authorized);
});
};
var lastGhUpdate = 0;
var authUsers = [];
var tenMinutes = 1000 * 60 * 10;
var getUsersOnTeam = function (teamId, cb) {
if ((new Date().getTime() - lastGhUpdate) < tenMinutes) return cb(null, authUsers);
lastGhUpdate = new Date().getTime();
getRequest('https://api.github.com/teams/' + teamId + '/members', function (err, res, body) {
if (err) return cb(err);
var usrsObj = JSON.parse(body);
authUsers = usrsObj.map(function (x) {
return x.login;
});
cb(null, authUsers);
});
};
var ghUrl = function (req) {
return 'https://github.com/login/oauth/authorize?client_id=' + clientId + '&scope=' + scope +
'&redirect_uri=' + redirectUri(req) + '&state=' + ghSecretState;
};
var cleanUrl = function (req) {
var u = url.parse(req.url, true);
delete u.search;
delete u.query.code;
delete u.query.state;
return url.format(u);
};
var login = function (req, res, next) {
redirect(ghUrl(req), res);
};
var logout = function (req, res, next) {
setCookie(res, cookieName, '');
next();
};
return {
decodeCookie: function (cookie) {
var val = cookie.match('(^|; )' + 'gh_uname' + '=([^;]*)');
val = val[2];
val = unescape(val);
return cookieSign.unsign(val, secret) || null;
},
authenticate: function (req, res, next) {
var cookie = getCookie(req, cookieName);
var val = cookie ? cookieSign.unsign(cookie, secret) : false;
var updateCode = function () {
if (config.autologin) return redirect(ghUrl(req), res);
delete req.github;
return next();
};
req.github = {};
if (val) {
req.github.authenticated = true;
req.github.user = val;
return next();
}
var u = url.parse(req.url, true);
if (!u.query.code || u.query.state !== ghSecretState) {
return updateCode();
}
rrs.post('https://github.com/login/oauth/access_token', {
headers: {
'User-Agent': userAgent
},
form: {
client_id: clientId,
client_secret: clientSecret,
code: u.query.code,
state: ghSecretState
},
timeout: 10000
}, function (err, response, body) {
if (err) return next(err);
var resp = url.parse('/?' + body, true);
if (!resp.query.access_token) {
return updateCode();
}
accessToken = resp.query.access_token;
getUser(function (err, ghusr) {
if (err) return next(err);
var checks = [];
if (config.users) checks.push(function (cb) {
cb(null, config.users.indexOf(ghusr) !== -1);
});
if (config.team) checks.push(function (cb) {
isInTeam(ghusr, cb);
});
if (config.organization) checks.push(function (cb) {
isInOrganization(cb);
});
async.parallel(checks, function (err, results) {
if (err) return next(err);
if (results.length === 0) return next(new Error('You have to add either users, team, or organizations to the config'));
var auth = results.every(function (el) {
return el;
});
if (!auth) {
req.github.authenticated = false;
req.github.user = ghusr;
if (config.autologin) return redirect(ghUrl(req), res);
return next();
}
var opts = {};
if (config.maxAge) opts.expires = new Date(Date.now() + config.maxAge);
setCookie(res, cookieName, cookieSign.sign(ghusr, secret), opts);
req.github.user = ghusr;
req.github.authenticated = true;
if (config.hideAuthInternals && (u.query.code || u.query.state)) {
return redirect(cleanUrl(req), res);
}
next();
});
});
});
},
login: login,
logout: logout
};
};