-
Notifications
You must be signed in to change notification settings - Fork 162
/
index.js
280 lines (219 loc) · 8.03 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
/**
* index.js
* OAuth 2.0 provider
*
* @author Amir Malik
*/
var EventEmitter = require('events').EventEmitter,
querystring = require('querystring'),
serializer = require('serializer');
_extend = function(dst,src) {
var srcs = [];
if ( typeof(src) == 'object' ) {
srcs.push(src);
} else if ( typeof(src) == 'array' ) {
for (var i = src.length - 1; i >= 0; i--) {
srcs.push(this._extend({},src[i]))
};
} else {
throw new Error("Invalid argument")
}
for (var i = srcs.length - 1; i >= 0; i--) {
for (var key in srcs[i]) {
dst[key] = srcs[i][key];
}
};
return dst;
}
function parse_authorization(authorization) {
if(!authorization)
return null;
var parts = authorization.split(' ');
if(parts.length != 2 || parts[0] != 'Basic')
return null;
var creds = new Buffer(parts[1], 'base64').toString(),
i = creds.indexOf(':');
if(i == -1)
return null;
var username = creds.slice(0, i);
password = creds.slice(i + 1);
return [username, password];
}
function OAuth2Provider(options) {
if(arguments.length != 1) {
console.warn('OAuth2Provider(crypt_key, sign_key) constructor has been deprecated, yo.');
options = {
crypt_key: arguments[0],
sign_key: arguments[1],
};
}
options['authorize_uri'] = options['authorize_uri'] || '/oauth/authorize';
options['access_token_uri'] = options['access_token_uri'] || '/oauth/access_token';
this.options = options;
this.serializer = serializer.createSecureSerializer(this.options.crypt_key, this.options.sign_key);
}
OAuth2Provider.prototype = new EventEmitter();
OAuth2Provider.prototype.generateAccessToken = function(user_id, client_id, extra_data, token_options) {
token_options = token_options || {}
var out = _extend(token_options, {
access_token: this.serializer.stringify([user_id, client_id, +new Date, extra_data]),
refresh_token: null,
});
return out;
};
OAuth2Provider.prototype.login = function() {
var self = this;
return function(req, res, next) {
var data, atok, user_id, client_id, grant_date, extra_data;
if(req.query['access_token']) {
atok = req.query['access_token'];
} else if((req.headers['authorization'] || '').indexOf('Bearer ') == 0) {
atok = req.headers['authorization'].replace('Bearer', '').trim();
} else {
return next();
}
try {
data = self.serializer.parse(atok);
user_id = data[0];
client_id = data[1];
grant_date = new Date(data[2]);
extra_data = data[3];
} catch(e) {
res.writeHead(400);
return res.end(e.message);
}
self.emit('access_token', req, {
user_id: user_id,
client_id: client_id,
extra_data: extra_data,
grant_date: grant_date
}, next);
};
};
OAuth2Provider.prototype.oauth = function() {
var self = this;
return function(req, res, next) {
var uri = ~req.url.indexOf('?') ? req.url.substr(0, req.url.indexOf('?')) : req.url;
if(req.method == 'GET' && self.options.authorize_uri == uri) {
var client_id = req.query.client_id,
redirect_uri = req.query.redirect_uri;
if(!client_id || !redirect_uri) {
res.writeHead(400);
return res.end('client_id and redirect_uri required');
}
// authorization form will be POSTed to same URL, so we'll have all params
var authorize_url = req.url;
self.emit('enforce_login', req, res, authorize_url, function(user_id) {
// store user_id in an HMAC-protected encrypted query param
authorize_url += '&' + querystring.stringify({x_user_id: self.serializer.stringify(user_id)});
// user is logged in, render approval page
self.emit('authorize_form', req, res, client_id, authorize_url);
});
} else if(req.method == 'POST' && self.options.authorize_uri == uri) {
var client_id = (req.query.client_id || req.body.client_id),
redirect_uri = (req.query.redirect_uri || req.body.redirect_uri),
response_type = (req.query.response_type || req.body.response_type) || 'code',
state = (req.query.state || req.body.state),
x_user_id = (req.query.x_user_id || req.body.x_user_id);
var url = redirect_uri;
switch(response_type) {
case 'code': url += '?'; break;
case 'token': url += '#'; break;
default:
res.writeHead(400);
return res.end('invalid response_type requested');
}
if('allow' in req.body) {
if('token' == response_type) {
var user_id;
try {
user_id = self.serializer.parse(x_user_id);
} catch(e) {
console.error('allow/token error', e.stack);
res.writeHead(500);
return res.end(e.message);
}
self.emit('create_access_token', user_id, client_id, function(extra_data,token_options) {
var atok = self.generateAccessToken(user_id, client_id, extra_data, token_options);
if(self.listeners('save_access_token').length > 0)
self.emit('save_access_token', user_id, client_id, atok);
url += querystring.stringify(atok);
res.writeHead(303, {Location: url});
res.end();
});
} else {
var code = serializer.randomString(128);
self.emit('save_grant', req, client_id, code, function() {
var extras = {
code: code,
};
// pass back anti-CSRF opaque value
if(state)
extras['state'] = state;
url += querystring.stringify(extras);
res.writeHead(303, {Location: url});
res.end();
});
}
} else {
url += querystring.stringify({error: 'access_denied'});
res.writeHead(303, {Location: url});
res.end();
}
} else if(req.method == 'POST' && self.options.access_token_uri == uri) {
var client_id = req.body.client_id,
client_secret = req.body.client_secret,
redirect_uri = req.body.redirect_uri,
code = req.body.code;
if(!client_id || !client_secret) {
var authorization = parse_authorization(req.headers.authorization);
if(!authorization) {
res.writeHead(400);
return res.end('client_id and client_secret required');
}
client_id = authorization[0];
client_secret = authorization[1];
}
if('password' == req.body.grant_type) {
if(self.listeners('client_auth').length == 0) {
res.writeHead(401);
return res.end('client authentication not supported');
}
self.emit('client_auth', client_id, client_secret, req.body.username, req.body.password, function(err, user_id) {
if(err) {
res.writeHead(401);
return res.end(err.message);
}
res.writeHead(200, {'Content-type': 'application/json'});
self._createAccessToken(user_id, client_id, function(atok) {
res.end(JSON.stringify(atok));
});
});
} else {
self.emit('lookup_grant', client_id, client_secret, code, function(err, user_id) {
if(err) {
res.writeHead(400);
return res.end(err.message);
}
res.writeHead(200, {'Content-type': 'application/json'});
self._createAccessToken(user_id, client_id, function(atok) {
self.emit('remove_grant', user_id, client_id, code);
res.end(JSON.stringify(atok));
});
});
}
} else {
return next();
}
};
};
OAuth2Provider.prototype._createAccessToken = function(user_id, client_id, cb) {
var self = this;
this.emit('create_access_token', user_id, client_id, function(extra_data, token_options) {
var atok = self.generateAccessToken(user_id, client_id, extra_data, token_options);
if(self.listeners('save_access_token').length > 0)
self.emit('save_access_token', user_id, client_id, atok);
return cb(atok);
});
};
exports.OAuth2Provider = OAuth2Provider;