-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
339 lines (290 loc) · 10.4 KB
/
app.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
var uuid = require('node-uuid');
var express = require('express');
var crypto = require('crypto');
var openid = require('openid');
var app = express();
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config/aws.json');
var s3 = new AWS.S3.Client();
var dynamo = new AWS.DynamoDB.Client() ;
app.set('view engine', 'ejs');
app.set('view options', {
layout: false
});
function customHeaders( req, res, next ){
app.disable('x-powered-by');
res.header("Server", "edeadlock OAuth Server v1.0");
next();
}
app.use(customHeaders);
app.use("/html", express.static(__dirname + '/public'));
/* Need to enable for oauth
app.use(function(req, res, next){
var auth_header = req.headers['authorization'];
if(!auth_header) {
res.status(401);
res.end('Authorization header not found');
return;
}
next();
});
*/
app.use(express.cookieParser());
app.use(express.session({secret: '3ea8c28773fd47d7be77b5e398542ba9'}));
app.use(app.router);
var relyingParty = new openid.RelyingParty(
'http://localhost/login/verify', // Verification URL (yours)
null, // Realm (optional, specifies realm for OpenID authentication)
false, // Use stateless verification
false, // Strict mode
[ new openid.AttributeExchange(
{
"http://axschema.org/contact/email": "required",
"http://axschema.org/namePerson/friendly": "required",
"http://axschema.org/namePerson": "required"
})]); // List of extensions to enable and include
var devrelyingParty = new openid.RelyingParty(
'http://localhost/login/verify', // Verification URL (yours)
null, // Realm (optional, specifies realm for OpenID authentication)
false, // Use stateless verification
false, // Strict mode
[ new openid.AttributeExchange(
{
"http://axschema.org/contact/email": "required",
"http://axschema.org/namePerson/friendly": "required",
"http://axschema.org/namePerson": "required"
})]); // List of extensions to enable and include
app.get('/login', function(req, res){
if(req.session.logged === true)
res.redirect("/oauth/authorize")
else
res.redirect("/html/index.html")
});
app.get('/dev/login', function(req, res){
if(req.session.logged === true)
res.redirect("/oauth/register")
else
res.redirect("/html/index.html")
});
app.get('/logout', function(req, res){
req.session.logged = false;
req.session.userId = null;
res.end("Good bye :(")
});
app.get('/login/authenticate', function(request, response) {
var identifier = request.query.openid_identifier;
// Resolve identifier, associate, and build authentication URL
relyingParty.authenticate(identifier, false, function(error, authUrl) {
if (error) {
response.writeHead(200);
response.end('Authentication failed: ' + error.message);
}
else if (!authUrl) {
response.writeHead(200);
response.end('Authentication failed');
}
else {
response.writeHead(302, { Location: authUrl });
response.end();
}
});
});
app.get('/login/verify', function(req, res) {
// Verify identity assertion
// NOTE: Passing just the URL is also possible
relyingParty.verifyAssertion(req, function(error, result) {
if(!error && result.authenticated) {
req.session.logged = true
req.session.userId = result.email
res.redirect("/oauth/register");
}
});
});
app.get('/oauth/register', function(req, res){
var app_name = req.query["app_name"]
var user_id = req.session.userId
if(app_name!=null) {
var app_desc = req.query["app_desc"];
var app_callback = req.query["app_callback"]
var consumer_key = uuid.v4().replace(/-/g,"")
var consumer_secret = crypto.randomBytes(32).toString('hex')
var params = {TableName : 'oauth_consumer', "Item":{
"consumer_key":{"S":consumer_key},
"consumer_secret":{"S":consumer_secret},
"user_id":{"S":user_id},
"app_name":{"S":app_name},
"app_desc":{"S":app_desc},
"callback_url":{"S":app_callback}
}
};
dynamo.putItem(params, function(err, data) {
if (err)
console.log(err)
else
console.log(data.Item.S('consumer_key'));
});
var params = {TableName : 'oauth_key_user', "Item":{
"consumer_key":{"S":consumer_key},
"user_id":{"S":user_id}
}
};
dynamo.putItem(params, function(err, data) {
if (err)
console.log(err)
else
console.log(data.Item.S('consumer_key'));
});
}
var AttributesToGet = new Array("user_id", "app_name", "app_desc","consumer_key","consumer_secret");
var params = {"TableName" : "oauth_consumer", "ScanFilter":{ "user_id": { "AttributeValueList":[{"S" : user_id}], "ComparisonOperator": "EQ"} }, "AttributesToGet": AttributesToGet };
dynamo.scan(params, function(err, data) {
if (err)
console.log(err)
else {
var token = crypto.randomBytes(32);
res.render('register', {
apps: data.Items
});
}
});
});
app.get('/oauth/authorize', function(req, res){
var welcome = 'Welcome';
if (req.session.logged) {
req.session.userId = req.query["user"];
console.log(req.query["user"]);
res.render('home', {
welcome: 'Welcome back! '+req.query["user"],
body : 'Mythri Pericharla'
});
}
else {
req.session.logged = true;
res.render('login', {
welcome: 'Welcome',
body : 'Mythri Pericharla'
});
}
});
app.get('/oauth/request_token', function(req, res){
/*
//Auth header
console.log(req.headers['authorization'])
var auth_header = req.headers['authorization']
if(typeof auth_header !== 'undefined') {
var auth_header_req = auth_header.split(" ")
var oauth_header = auth_header_req[0]
if(oauth_header === 'OAuth') {
var auth_headers = auth_header_req[1].split(",")
console.log("type = "+oauth_header)
console.log("elements = "+auth_headers[0])
}
}
//POST body
var content_type = req.headers['content-type']
if(typeof content_type !== 'undefined') {
if(content_type === 'application/x-www-form-urlencoded') {
console.log('check POST body')
}
}
*/
//query params
request_token(req, res);
});
app.get('/oauth/auth_token', function(req, res){
res.render('token', {
body : uuid.v4().replace(/-/g,"")
});
});
app.get('/oauth/test', function(req, res){
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
res.write(req.method + ' ' + req.protocol + '://' + req.host + req.url);
res.end('\r\n'+fruits[0]);
});
function request_token(req, res) {
var required = ['oauth_consumer_key','oauth_signature_method','oauth_signature','oauth_timestamp','oauth_nonce','oauth_callback'];
var required_value = [];
var required_ordered = [];
var required_tosign;
required_tosign = req.method + '&' + encodeURIComponent(req.protocol + '://' + req.host + req.route.path) + '&'
for(x in required) {
if(typeof req.query[required[x]] === 'undefined') {res.end("query params missing: "+required[x]); return;}
required_value[x] = req.query[required[x]];
//console.log(required[x] +" = "+ required_value[x])
if(required[x] !== 'oauth_signature')
required_ordered[x]=required[x] +'='+ required_value[x]
}
required_ordered.sort()
for(x in required_ordered) {
required_tosign = required_tosign + encodeURIComponent(required_ordered[x]);
}
console.log(required_tosign)
var signature = crypto.createHmac('sha1', 'gfyitftyifyftft').update(required_tosign).digest('hex')
console.log(signature)
var signatureMethod = required_value[required.indexOf('oauth_signature_method')];
if( signatureMethod.toUpperCase() != "PLAINTEXT" && signatureMethod.toUpperCase() != "HMAC-SHA1") { res.end("signature type not allowed: use 'PLAINTEXT' or 'HMAC-SHA1'"); return; }
var version = required_value[required.indexOf('oauth_version')];
if( version != "1.0" ) { res.end("versions allowed: 1.0"); return; }
var AttributesToGet = new Array("consumer_key", "user_id");
var params = {"TableName" : "oauth_key_user", "Key":{ "HashKeyElement": {"S" : String(required_value[required.indexOf('oauth_consumer_key')]) }}, "AttributesToGet": AttributesToGet };
dynamo.getItem(params, function(err, data) {
if (err) {
console.log(err)
res.end("Invalid request."); return;
}
else {
if(Object.keys(data).length == 1) {
res.end("Invalid request. Error Code: 1"); return;
}
else {
var response = data.Item.user_id.S
}
}
});
var oauth_token = uuid.v4().replace(/-/g,"")
var oauth_token_secret = crypto.randomBytes(32).toString('hex')
var oauth_callback_confirmed = "true"
var oauth_expires_in = 3600
res.redirect(String(required_value[required.indexOf('oauth_callback')])
+"?oauth_token=" + oauth_token +
"&oauth_token_secret=" + oauth_token_secret +
"&oauth_callback_confirmed=" + oauth_callback_confirmed +
"&oauth_expires_in=" + oauth_expires_in)
}
function access_token(req, res) {
var required = ['oauth_consumer_key','oauth_token','oauth_signature_method','oauth_signature','oauth_timestamp',
'oauth_nonce','oauth_version','oauth_verifier'];
var required_value = [];
for(x in required) {
if(typeof req.query[required[x]] === 'undefined') {res.end("query params missing: "+required[x]); return;}
required_value[x] = req.query[required[x]];
console.log(required[x] +" = "+ required_value[x])
}
var signatureMethod = required_value[required.indexOf('oauth_signature_method')];
if( signatureMethod.toUpperCase() != "PLAINTEXT" && signatureMethod.toUpperCase() != "HMAC-SHA1") { res.end("signature type not allowed: use 'PLAINTEXT' or 'HMAC-SHA1'"); return; }
var version = required_value[required.indexOf('oauth_version')];
if( version != "1.0" ) { res.end("versions allowed: 1.0"); return; }
var AttributesToGet = new Array("consumer_key", "user_id");
var params = {"TableName" : "oauth_key_user", "Key":{ "HashKeyElement": {"S" : String(required_value[required.indexOf('oauth_consumer_key')]) }}, "AttributesToGet": AttributesToGet };
dynamo.getItem(params, function(err, data) {
if (err) {
console.log(err)
res.end("Invalid request."); return;
}
else {
if(Object.keys(data).length == 1) {
res.end("Invalid request. Error Code: 1"); return;
}
else {
var response = data.Item.user_id.S
}
}
});
var oauth_token = uuid.v4().replace(/-/g,"")
var oauth_token_secret = crypto.randomBytes(32).toString('hex')
res.redirect("oauth_token=" + oauth_token +
"&oauth_token_secret=" + oauth_token_secret)
}
app.listen(80);
console.log('Server listening on port 80...');