This repository has been archived by the owner on Mar 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
executable file
·739 lines (658 loc) · 22.3 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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
// load config
var jf = require("jsonfile");
var fs = require("fs");
var CONFIG = fs.existsSync('./config.json') ? jf.readFileSync('config.json') : {};
var SAMPLE_CONFIG = jf.readFileSync('config.sample.json')
// inject data from ENV if it exists
// get ENV variables with corresponding names,
// if they exist, override the files data
for ( var config_key in SAMPLE_CONFIG ) {
if(!CONFIG.hasOwnProperty(config_key)){
CONFIG[config_key] = process.env[config_key.toUpperCase()]
}
}
var express = require('express');
var favicon = require('serve-favicon');
var redis = require('redis');
var request = require('request');
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
var constants = require("./jsx/constants.js");
// redis setup
/////////////////
try{
// used for the debug/staging/alpha server
function makeRedisClient (redis_db) {
var rv = null
if(process.env.REDISTOGO_URL){
var rtg = require("url").parse(process.env.REDISTOGO_URL);
rv = redis.createClient(rtg.port, rtg.hostname);
rv.auth(rtg.auth.split(":")[1]);
}else{
rv = redis.createClient('6379',CONFIG['redis_address']);
}
rv.select(redis_db);
rv.on('connect', function() {
console.log('Connected to redis#'+redis_db.toString());
});
return rv
}
var redis_client = makeRedisClient(0);
var legacy_redis_client = makeRedisClient(1);
}catch (e){
// in case redis doesn't exist
console.log(e)
}
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
// TODO: change settings if we want to handle secure cookies explicitly
// https://github.com/expressjs/session#cookie-options
// if (app.get('env') === 'production') {
// app.set('trust proxy', 1) // trust first proxy
// sess.cookie.secure = true // serve secure cookies
// }
var connect_redis_options = {
db: 0
}
if(process.env.REDISTOGO_URL){
var rtg = require("url").parse(process.env.REDISTOGO_URL);
connect_redis_options.port = rtg.port
connect_redis_options.host = rtg.hostname
connect_redis_options.pass = rtg.auth.split(":")[1]
}else{
connect_redis_options.port = 6379
connect_redis_options.host = CONFIG['redis_address']
}
app.use(session({
store: new RedisStore(connect_redis_options),
// cookie: { maxAge: 60000*60*24*30 }
secret: CONFIG['session_secret'],
resave: false,
saveUninitialized: false
}));
redis_client.exists('twitchuser:iliedaboutcake', function (e, r) {
if(r == 1){
console.log("no need to add the default user, redis says ", r)
return
}
console.log("adding the default user to redis")
// test layout of how we should probably format redis users
redis_client.hmset(
'user:dank_memester', //change able overrustle user name
'overrustle_username', 'dank_memester',
'stream', '19949118', //stream set from their profile
'service', 'ustream', //service set from their profile
'twitch_user_id','30384275', //twitch user ID from OAuth
'twitchuser', 'iliedaboutcake', //twitch username
'admin', 'true',
'allowchange', 'false', //allows the user to change username if set to 1
'lastseen', new Date().toISOString(), //keep track of last seen
'lastip','127.0.0.1'); //IP address for banning and auditing
// maintain in index of twitchuser -> overrustle_username
redis_client.set(
'twitchuser:iliedaboutcake',
'dank_memester' //change able overrustle user name
);
})
/////////////////
app.listen(CONFIG['port']);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs');
//handle static content
app.use("/css", express.static(__dirname + '/css'));
app.use("/js", express.static(__dirname + '/js'));
app.use("/img", express.static(__dirname + '/img'));
app.use("/html", express.static(__dirname + '/html'));
app.use("/fonts", express.static(__dirname + '/fonts'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(function (req, res, next) {
// console.log("middleware setting current user")
console.log(Date.now(), req.method, req.originalUrl);
if (req.session.user_id) {
console.log('fetching sessions user', req.session.user_id)
redis_client.hgetall("user:"+req.session.user_id, function(err, found_user) {
// console.log(resp, err)
if(err){
console.error('error fetching user', err)
return next(err)
}
req.session.save(function (serr){
if(serr){
console.error('error saving user', serr)
return next(serr)
}
res.locals.current_user = found_user;
next()
})
});
}else{
next()
}
});
app.use(function (req, res, next) {
// console.log("middleware popping notices")
noticePop(req).then(function (notice){
res.locals.notice = notice
next()
})
})
global.SERVICES = constants.SERVICES;
global.SERVICE_NAMES = Object.keys(constants.SERVICES);
global.TWITCH_OAUTH_URL = 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code' +
'&client_id=' + CONFIG['twitch_client_id'] +
'&redirect_uri=' + CONFIG['twitch_redirect_uri'] +
'&scope=user_read';
// This is our React component, shared by server and browser thanks to browserify
/////////////////
// server side react js
var React = require('react');
var App = React.createFactory(require('./js/App'))
// cache the stream list from the API
// so that the HTML we serve on first load is fresh
/////////////////
var static_api_data = {}
function getApiData(){
request.get({json:true, uri:"https://api.overrustle.com/api"}, function (e, r, resp) {
if(e){
console.log("error getting new data", JSON.stringify(e))
return e
}
var json = resp
// api_data.live = r.statusCode < 400 && json.hasOwnProperty('status') && json['status'] !== 404
//handle the streams listing here
static_api_data = json
})
}
getApiData()
var apiRefresher = setInterval(getApiData, 2000)
// For the Future:
// This will require a rewrite on the server side to implement correctly
// var socket = require('socket.io-client')('https://api.overrustle.com/streams');
// socket.on('connect', function(){
// console.log("Connected SOCKET")
// // we cannot infer this from the referrer because <------------ IMPORTANT
// // there is no way to set a referrer with this client <-------- IMPORTANT
// socket.emit("idle", {"/strims"})
// });
// socket.on('strims', function(api_data){
// console.log(api_data)
// });
// socket.on('disconnect', function(){
// console.log("DISCONNECTED SOCKET")
// });
/////////////////
app.get (['/', '/strims', '/streams'], function(req, res, next) {
// trying out sessions
// var sess = req.session;
// if (!sess.views) {
// sess.views = 0
// }
// sess.views = sess.views + 1;
var props = {
api_data: static_api_data
}
var page_title = Object.keys(static_api_data.streams).length + " Live Streams viewed by " + static_api_data.viewercount + " rustlers"
res.render("layout", {
page: "streams",
page_title: page_title,
react_props: props,
rendered_streams: React.renderToString(App(props))
})
});
app.post("/channel", function(req, res, next){
})
app.get ('/profile', function(req, res, next) {
// set header don't cache
res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.setHeader('Expires', '-1');
res.setHeader('Pragma', 'no-cache');
if (res.locals.current_user) {
// console.log('rendering layout')
// clear out notices
res.render("layout", {
page: "profile",
page_title: "Profile for "+res.locals.current_user.overrustle_username
})
}else{
// console.log('redirecting home')
res.redirect('/')
}
})
//THIS DOES NOT WORK
app.use('/admin*', function(req, res, next){
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
// set header: don't cache
// then nginx doesn't cache it
if(res.locals.current_user && res.locals.current_user.admin == "true"){
next()
}else{
console.log("nonadmin user:", res.locals.current_user)
noticeAdd(req, {"danger": "You are not allowed to access that page"})
.then(function(){
res.redirect('/')
})
}
})
var Promise = require('bluebird')
app.get ('/admin', function(req, res, next) {
//get all the users
var site_users = []
new Promise(function (resolve, reject) {
redis_client.keys('user:*', function (err, keys) {
if (err) reject(err);
resolve(keys);
});
})
.then(function (keys) {
return Promise.all(keys.map(function (key) {
return new Promise(function (resolve, reject) {
redis_client.hgetall(key, function (err, res) {
if (err) reject(err);
site_users.push(res);
resolve();
});
});
}));
})
.then(function () {
// console.log(site_users);
res.render("layout", {
page: "admin",
page_title: "Admin Signed in as " + res.locals.current_user.overrustle_username,
users: site_users
})
});
})
//get all of dat dirty NSA info from their profile
app.get ('/admin/:overrustle_username', function(req, res, next) {
redis_client.hgetall("user:"+req.params.overrustle_username, function(err, resp) {
user_info = resp
res.render("layout", {
page: "adminuser",
page_title: "Editing: " + user_info.overrustle_username,
user: user_info
})
});
})
app.post ('/admin/ban', function (req, res, next){
var name = req.body.name
var reason = req.body.reason
redis_client.hmset('banlist', name, reason, function (err, result){
if(err){
return console.error(err)
}
noticeAdd(req, {"success": "Banned "+name+" for "+reason})
.then(function(){
res.redirect('/admin')
})
})
})
// edit a username -- admin editing, or user editing
app.post('/profile/:original_overrustle_username', function (req, res, next) {
var current_user = res.locals.current_user;
var original_username = req.params.original_overrustle_username;
console.log("current_user:", current_user)
console.log('editing user:', 'original_username', req.params, 'new_data', req.body)
if(current_user.admin != "true" && current_user.overrustle_username != original_username){
return noticeAdd(req, {"danger":"You're not allowed to edit "+original_username+"\'s channel"}).then(function(){
res.redirect('/')
})
}
// TODO:
// validate that overrustle_username in body is the same as original name
// unless user is able to change it
var new_username = req.body.overrustle_username ? req.body.overrustle_username.toLowerCase() : original_username.toLowerCase()
new Promise(function (resolve, reject){
redis_client.hgetall("user:"+original_username, function(err, resp) {
if (err) reject(err);
resolve(resp)
})
}).then(function (user){
// merge in new user settings
return new Promise(function (resolve, reject){
user.service = req.body.service
user.stream = req.body.stream
// only an admin can grant name changes
if(current_user.admin === "true"){
user.allowchange = req.body.allowchange
}else{
console.log("NOPE you cant give yourself a name change")
}
// figure out if you're allowed to change your name
var canChange = (current_user.admin === "true" || user.allowchange === "true") && new_username.length > 0
if (!canChange && original_username != new_username) {
// trying to change your name despite being unable to
return noticeAdd(req, {"warning": "You can\'t change your overustle.com username more than once. Ask ILiedAboutCake or hephaestus for a name change."})
.then(function (){
resolve([current_user, user])
})
}
// if we're not changing the name, don't bother
// checking for duplicates
if(new_username == original_username){
return resolve([current_user, user])
}
return redis_client.exists("user:"+new_username, function (err, rsp) {
var does_exist = rsp == 1
if(does_exist){
return noticeAdd(req, {"danger":"You\'re Not allowed to change your name to an existing user\'s name: "+new_username})
.then(function(){
resolve([current_user, user])
})
}else{
user.overrustle_username = new_username
resolve([current_user, user])
}
})
})
}).spread(function (current_user, user){
// only allow 1 name change
if(current_user.admin !== "true"){
console.log("not an admin, so no more name changes")
user.allowchange = "false"
}
// set the twitch -> overrustle index
return new Promise(function (resolve, reject){
redis_client.set(
"twitchuser:"+user.twitchuser,
user.overrustle_username,
function (err, reply) {
if(err) reject(err);
resolve(user)
}
)
})
}).then(function (user){
return new Promise(function (resolve, reject){
redis_client.hmset('user:'+user.overrustle_username, user, function(err, result){
if(err){
return console.error(err)
}
noticeAdd(req, {"success": user.overrustle_username+"\'s profile updated sucessfully!"})
// make sure you're not changing **from another person's** name
if(res.locals.current_user.overrustle_username === original_username){
res.locals.current_user = user
req.session.user_id = user.overrustle_username
req.session.save(function (serr){
if(serr){
reject(serr)
}
resolve(user)
})
}else{
console.log("DERP not setting an admin's session to another persons")
resolve(user)
}
})
})
}).then(function (user) {
// if we made a successful name change
// clean out the old record
return new Promise(function (resolve, reject){
if (user.overrustle_username == original_username) {
return resolve(user)
}else{
redis_client.del('user:'+original_username, function(err, resp){
if(err){
console.error(err)
}
resolve(user)
})
}
})
}).then(function (user) {
if(res.locals.current_user.admin === 'true'){
res.redirect('/admin/'+user.overrustle_username)
}else{
res.redirect('/profile')
}
})
})
// TODO:
// enforce uniqueness of platform+channel (service+stream)
// twitch will send oauth requests
// that use our client_id to this path
app.get("/oauth/twitch", function(req, res, next){
if(req.query.error){
noticeAdd(req, {"danger":"Twitch Login did not work. Twitch says: "+req.query.error+": "+req.query.error_description})
return res.redirect('/')
}
if(!req.query.code){
return next()
}
request.post({
url: constants["TWITCH_TOKEN_URL"],
form: {
client_id: CONFIG['twitch_client_id'],
client_secret: CONFIG['twitch_client_secret'],
grant_type: "authorization_code",
redirect_uri: CONFIG['twitch_redirect_uri'],
code: req.query.code
},
json: true
}, function (e, r, body) {
if(e){
console.log("error getting access_token from twitch", JSON.stringify(e))
return e
}
var jt = body;
console.log('twitch token body', body)
// {
// "access_token": "[user access token]",
// "scope":[array of requested scopes]
// }
var twitch_user_url = "https://api.twitch.tv/kraken/user?oauth_token="+jt['access_token'];
request.get({
json:true,
uri:twitch_user_url
}, function (e, r, resp) {
if(e){
console.log("error looking up user data using access_token", JSON.stringify(e))
return e
}
var json = resp
if(json['status'] >= 300){
console.log()
}
// use the twitch -> overrustle index to find the right username
redis_client.get("twitchuser:"+json['name'], function(e, reply) {
if(e){
console.log("error getting new data", e)
return e
}
// reply is null when the key is missing
var new_settings = {}
new_settings['lastseen'] = new Date().toISOString();
new_settings['lastip'] = req.headers.hasOwnProperty('x-forwarded-for') ? req.headers['x-forwarded-for'] : req.connection.remoteAddress
var overrustle_username = reply;
if(overrustle_username == null){
overrustle_username = json['name'];
// ensure the index is consistent
redis_client.set('twitchuser:'+overrustle_username, overrustle_username, redis.print)
new_settings['overrustle_username'] = overrustle_username
new_settings['twitchuser'] = json["name"]
new_settings['stream'] = json["name"]
new_settings['service'] = "twitch"
new_settings['twitch_user_id'] = json['_id']
// TODO: decide if we want to
// allow new users to change their overrustle_username
new_settings['allowchange'] = "true"
new_settings['admin'] = "false"
}
console.log(reply, new_settings);
redis_client.hmset(
'user:'+overrustle_username,
new_settings,
function(err, result){
redis_client.hgetall('user:'+overrustle_username, function(err, returned) {
if(err){
return next(err)
}
res.locals.current_user = returned;
req.session.user_id = overrustle_username
req.session.save(function (sess_err){
if(sess_err){
return next(sess_err)
}
noticeAdd(req, {"success":"Congrats "+overrustle_username+", You are now logged into OverRustle.com"})
res.redirect('/profile')
})
});
});
});
});
});
});
app.get('/logout', function (req, res, next) {
req.session.user = undefined
req.session.user_id = undefined
req.session.save(function (err){
if(err){
return next(err)
}
noticeAdd(req, {"success":"You logged out sucessfully!"})
res.redirect('/')
})
})
// WARNING: if you get an ADVANCED stream with
// hashbangs in the URL they won't get past the form
app.get (['/destinychat', '/:service/:stream'], function(req, res, next) {
//handle normal streaming services here
// redirect to modern urls from the form
if(req.query.hasOwnProperty("s") || req.query.hasOwnProperty("stream")){
return res.redirect("/"+req.query.s+"/"+req.query.stream)
}
if (req.params.service && global.SERVICE_NAMES.indexOf(req.params.service) !== -1) {
validateBanned(req.params.stream, req, res, function (err) {
// console.log("Good Validation!")
res.render("layout", {
page: "service",
page_title: req.params.stream + ' on ' + req.params.service,
stream: req.params.stream,
service: req.params.service
})
})
}else if (req.params.service || req.params.stream){
console.log('bad channel')
console.log(req.params.service, 'not in:')
console.log(global.SERVICE_NAMES)
noticeAdd(req, {"danger": "You visited /destinychat without specifying a stream or service"})
return res.redirect('/')
}else{
var props = {
api_data: static_api_data
}
var page_title = "Destiny.gg chat with " + Object.keys(static_api_data.streams).length + " Live Streams viewed by " + static_api_data.viewercount + " rustlers"
res.render("layout", {
page: "destinychat",
page_title: page_title,
react_props: props,
rendered_streams: React.renderToString(App(props))
})
}
});
app.get (['/channel', '/:channel'], function(req, res, next) {
var channel = null
// NOTE: channel will be undefined when on /channel specifically
// req.params still contains a key for 'channel'
// but it points to undefined
if(req.params.channel){
channel = req.params.channel.toLowerCase()
}
// LEGACY SUPPORT DELETE THIS EVENTUALLY
if(channel == null && req.query.hasOwnProperty('user')){
return res.redirect('/'+req.query.user)
}
if(channel == null){
console.log('no channel specified')
noticeAdd(req, {"danger": "You visited /channel without specifying a channel"})
return res.redirect('/')
}
//handle the channel code here, look up the channel in redis
redis_client.hgetall('user:' + channel, function(err, returned) {
if (returned) {
validateBanned(returned.stream, req, res, function (err) {
res.render("layout", {
page: "service",
page_title: channel + " via " + returned.stream + " on " + returned.service,
stream: returned.stream,
service: returned.service
})
})
} else {
// DELETE THIS
// support legacy channels as long as we feel like
legacy_redis_client.hgetall('channel:' + channel, function(lerr, lreturned){
if(lreturned){
res.render("layout", {
page: "service",
page_title: channel + " via " + lreturned.stream + " on " + lreturned.service,
stream: lreturned.stream,
service: lreturned.service
})
}else{
console.log('no channel found for', channel)
next();
}
})
}
})
})
//handle 404s
app.use(function(req, res, next) {
res.status(404);
url = req.url;
res.render('layout', {
page: '404',
page_title: 'Not Found',
url: url
}
);
});
function validateBanned (stream, req, res, cb) {
redis_client.hmget('banlist', stream, function (berr, breturnedarr) {
if(berr){
return next(berr)
}
var breturned = breturnedarr[0]
if (breturned) {
console.log('got isBanned', breturned)
noticeAdd(req, {"danger": stream+" is banned. "+breturned})
res.redirect('/')
}else{
cb(berr)
}
})
}
// move to notice.js
function noticeAdd(req, obj){
return new Promise(function (resolve, reject){
req.session.notice = req.session.notice ? req.session.notice : []
req.session.notice.push(obj)
req.session.save(function (err){
if(err){
return reject(err)
}
resolve()
})
})
}
function noticePop(req){
return new Promise(function (resolve, reject){
// console.log("flushing notices!")
var tmpnotice = req.session.notice
req.session.notice = undefined
req.session.save(function (err) {
if(err){
return reject(err)
}
resolve(tmpnotice)
})
})
}