-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
447 lines (411 loc) · 12.5 KB
/
app.js
File metadata and controls
447 lines (411 loc) · 12.5 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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
/*
* https://nutty.io
* Copyright (c) 2013 krishna.srinivas@gmail.com All rights reserved.
* AGPLv3 License <http://www.gnu.org/licenses/agpl-3.0.txt>
*/
var express = require('express'),
passport = require('passport'),
util = require('util'),
GoogleStrategy = require('passport-google').Strategy,
crypto = require('crypto'),
check = require('validator').check,
AWS = require('aws-sdk'),
MongoStore = require('connect-mongo')(express);
AWS.config.loadFromPath('./config.json');
var s3 = new AWS.S3();
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(obj, done) {
done(null, obj);
});
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nuttyapp');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
console.log("mongodb opened!");
});
var UserSchema = new mongoose.Schema({
fname: String,
lname: String,
email: {
type: String,
index: {
unique: true
}
},
username: {
type: String,
index: {
unique: true
}
},
recordings: []
});
var User = mongoose.model('user', UserSchema);
var RecordingSchema = new mongoose.Schema({
desc: String,
creator: String
});
var Recording = mongoose.model('Recording', RecordingSchema);
passport.use(new GoogleStrategy({
returnURL: 'http://localhost:3000/api/auth/google/return',
realm: 'http://localhost:3000/',
ui: {
mode: 'popup'
},
stateless: true,
profile: true
},
function(identifier, profile, done) {
process.nextTick(function() {
User.findOne({
'email': profile.emails[0].value
}, function(err, user) {
if (err) {
return done(null, null);
}
if (user) {
//profile.identifier = identifier;
profile.username = user.username;
return done(null, profile);
} else {
return done(null, profile);
}
});
});
}
));
var app = express.createServer();
// configure Express
app.configure(function() {
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({
secret: 'not a secret',
store: new MongoStore({
db: 'nuttyapp'
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.get('/api/policy/upload/:desc', function(req, res) {
if (!loggedin(req)) {
res.json({
error: "auth",
errormsg: "User Authentication required"
});
return;
}
try {
check(req.params.desc).len(1,30).is(/^[a-zA-Z][a-zA-Z0-9-,.:\s]+$/);
} catch (ex) {
res.json({
error: "error",
errormsg: ex.message
});
return;
}
User.findOne({
'username': req.user.username
}, function(err, user) {
if (err) {
res.json({
error: "unknown",
errormsg: "User not found in DB"
});
return;
}
if (user.recordings.length == 10) {
res.json({
error: "unknown",
errormsg: "number of recordings upload limit = 10"
});
return;
}
var recording = new Recording({
desc: req.params.desc,
creator: user.username
});
recording.save(function(err) {
if (err) {
res.json({
error: "unknown",
errormsg: "Error saving recording"
});
return;
}
user.recordings.push(recording._id.toString() + ":" + req.params.desc);
user.save(function(err) {
if (err) {
res.json({
error: "unknown",
errormsg: "Error saving recording to user profile"
});
return;
}
var bucket = "nutty";
var key = recording._id.toString();
var acl = "private";
var type = "application/binary";
var accessid = AWS.config.credentials.accessKeyId;
var secret = AWS.config.credentials.secretAccessKey;
var Expiration = new Date;
Expiration.setSeconds(24*60*60); // expire in one day
var JSON_POLICY = {
// "expiration": "2020-01-01T00:00:00Z",
"expiration": Expiration.getFullYear()+'-'+(Expiration.getMonth()+1)+'-'+Expiration.getDate()+'T'+Expiration.getHours()+':'+
Expiration.getMinutes()+':'+Expiration.getSeconds()+'Z',
"conditions": [{
"bucket": bucket
},
["starts-with", "$key", key], {
"acl": acl
},
["starts-with", "$Content-Type", type],
["content-length-range", 0, 1048576]
]
};
var policy = new Buffer(JSON.stringify(JSON_POLICY)).toString('base64');
var signature = crypto.createHmac('sha1', secret).update(policy).digest('base64');
var retobj = {
key: key,
AWSAccessKeyId: accessid,
acl: acl,
policy: policy,
signature: signature,
ContentType: type,
}
res.json(retobj);
});
});
});
});
app.get('/api/policy/download/:recid', function(req, res) {
Recording.findOne({
_id: req.params.recid
}, function(err, recording) {
if (!recording) {
res.json({
error: "unknown",
errormsg: "Unable to find the recording: " + req.params.recid
});
return;
}
var accessid = AWS.config.credentials.accessKeyId;
var secret = AWS.config.credentials.secretAccessKey;
var ContentMD5 = "";
var ContentType = "";
var Expires;
var expirytime = new Date();
expirytime.setSeconds(1000);
Expires = Math.floor(expirytime.getTime() / 1000);
var StringToSign = "GET" + "\n" +
ContentMD5 + "\n" +
ContentType + "\n" +
Expires + "\n" +
"/nutty/" + req.params.recid;
var signature = crypto.createHmac('sha1', secret).update(StringToSign).digest('base64');
var retobj = {
AWSAccessKeyId: accessid,
Expires: Expires,
Signature: signature
};
res.json(retobj);
return;
});
});
app.get('/api/policy/remove/:recid/:desc', function(req, res) {
if (!loggedin(req)) {
res.json({
error: "auth",
errormsg: "User Authentication required"
});
return;
}
Recording.findOne({
_id: req.params.recid
}, function(err, recording) {
if (err) {
res.json({
error: "error",
errormsg: "Unable to find the record"
});
return;
}
if (recording.creator != req.user.username) {
res.json({
error: "auth",
errormsg: "User not the creator of recording"
});
return;
}
s3.deleteObject({Bucket: 'nutty', Key: req.params.recid}, function(err, data) {
if (err) {
}
});
recording.remove(function(err) {
User.findOne({
username: recording.creator
}, function(err, user) {
if (err) {
res.json({
error: "error",
errormsg: "Unable to find the record"
});
return;
}
user.recordings.remove(req.params.recid + ":" + req.params.desc);
user.save();
res.json({
success: true
});
return;
});
});
});
});
app.get('/api/auth/google/return', function(req, res, next) {
passport.authenticate('google', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.json({
error: "auth",
errormsg: "Authentication failed"
});
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
if (user.username)
return res.send('<html><body><script>window.close()</script></body></html>');
else
return res.redirect('https://nutty.io/username.html');
});
})(req, res, next);
});
app.get('/api/auth/failed', function(req, res) {
res.send("Auth Failed");
});
app.get('/api/auth/google/logout', function(req, res) {
req.logout();
res.send("logged out");
});
app.get('/api/user/info', function(req, res) {
if (!req.isAuthenticated(req)) {
res.json({
error: "auth",
errormsg: "User Authentication required"
});
return;
}
res.json(req.user);
});
app.get('/api/user/detail', function(req, res) {
if (!loggedin(req)) {
res.json({
error: "auth",
errormsg: "User Authentication required"
});
return;
}
User.findOne({
'username': req.user.username
}, function(err, user) {
if (user) {
// user for some reason is immutable
user = JSON.parse(JSON.stringify(user));
delete user._id;
}
res.json(user);
});
});
app.post('/api/user/username', function(req, res) {
var username;
if (!req.isAuthenticated()) {
res.json({
error: "auth",
errormsg: "User Authentication required"
});
return;
}
username = req.param('username');
try {
check (username).len(4,20).isLowercase().is(/^[a-z]+$/).notRegex("^api").notRegex("^info").notRegex("^home").notRegex("^share").notRegex("^recording");
} catch (ex) {
res.json({
error: "error",
errormsg: "Username should be 4-20 chars and lowercase"
});
return;
}
User.findOne({
'username': username
}, function(err, user) {
if (err) {
res.json({
error: "error",
errormsg: "db query error"
});
return;
}
if (user) {
res.json({
error: "inuse",
errormsg: "username already in use"
});
return;
}
User.findOne({
'email': req.user.emails[0].value
}, function(err, user) {
if (err) {
res.json({
error: "error",
errormsg: "db query error"
});
return;
}
if (user) {
res.json({
error: "error",
errormsg: "emailid found in db"
});
// FIXME: update username
return;
}
user = new User({
fname: req.user.name.givenName,
lname: req.user.name.familyName,
email: req.user.emails[0].value,
username: req.param('username')
});
user.save(function(err) {
if (err)
res.json({
error: "error",
errormsg: "unable to save username to db"
});
else {
req.user.username = user.username;
res.json({
success: "registeded"
});
}
return;
});
});
});
});
app.listen(3000);
function loggedin(req) {
return (req.user && req.user.username);
}