forked from compdemocracy/polis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
14943 lines (13171 loc) · 518 KB
/
server.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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2012-present, Polis Technology Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
"use strict";
const akismetLib = require('akismet');
const AWS = require('aws-sdk');
AWS.config.set('region', 'us-east-1');
const badwords = require('badwords/object');
const Promise = require('bluebird');
const http = require('http');
const httpProxy = require('http-proxy');
// const Promise = require('es6-promise').Promise,
const sql = require("sql"); // see here for useful syntax: https://github.com/brianc/node-sql/blob/bbd6ed15a02d4ab8fbc5058ee2aff1ad67acd5dc/lib/node/valueExpression.js
const escapeLiteral = require('pg').Client.prototype.escapeLiteral;
const pg = require('pg').native; //.native, // native provides ssl (needed for dev laptop to access) http://stackoverflow.com/questions/10279965/authentication-error-when-connecting-to-heroku-postgresql-databa
const parsePgConnectionString = require('pg-connection-string').parse;
const async = require('async');
const FB = require('fb');
const fs = require('fs');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
const Intercom = require('intercom.io'); // https://github.com/tarunc/intercom.io
const IntercomOfficial = require('intercom-client');
const isTrue = require('boolean');
const OAuth = require('oauth');
// const Pushover = require('pushover-notifications');
// const pushoverInstance = new Pushover({
// user: process.env.PUSHOVER_GROUP_POLIS_DEV,
// token: process.env.PUSHOVER_POLIS_PROXY_API_KEY,
// });
// const postmark = require("postmark")(process.env.POSTMARK_API_KEY);
const querystring = require('querystring');
const devMode = isTrue(process.env.DEV_MODE);
const replaceStream = require('replacestream');
const responseTime = require('response-time');
const request = require('request-promise'); // includes Request, but adds promise methods
const s3Client = new AWS.S3({apiVersion: '2006-03-01'});
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const LruCache = require("lru-cache");
const timeout = require('connect-timeout');
const Translate = require('@google-cloud/translate');
const isValidUrl = require('valid-url');
const zlib = require('zlib');
const _ = require('underscore');
var WebClient = require('@slack/client').WebClient;
var web = new WebClient(process.env.SLACK_API_TOKEN);
// const winston = require("winston");
const winston = console;
const emailSenders = require('./email/sendEmailSesMailgun').EmailSenders(AWS);
const sendTextEmail = emailSenders.sendTextEmail;
const sendTextEmailWithBackupOnly = emailSenders.sendTextEmailWithBackupOnly;
const resolveWith = (x) => { return Promise.resolve(x);};
const intercomClient = !isTrue(process.env.DISABLE_INTERCOM) ? new IntercomOfficial.Client('nb5hla8s', process.env.INTERCOM_API_KEY).usePromises() : {
leads: {
create: resolveWith({body: {user_id: "null_intercom_user_id"}}),
update: resolveWith({}),
},
};
const useTranslateApi = isTrue(process.env.SHOULD_USE_TRANSLATION_API);
let translateClient = null;
if (useTranslateApi) {
const GOOGLE_CREDS_TEMP_FILENAME = ".google_creds_temp";
fs.writeFileSync(GOOGLE_CREDS_TEMP_FILENAME, process.env.GOOGLE_CREDS_STRINGIFIED);
translateClient = Translate({
projectId: JSON.parse(fs.readFileSync(GOOGLE_CREDS_TEMP_FILENAME)).project_id,
});
}
// var conversion = {
// contact: { user_id: '8634dd66-f75e-428d-a2bf-930baa0571e9' },
// user: { email: '[email protected]', user_id: "12345" },
// };
// intercomClient.leads.convert(conversion).then((o) => {
// console.error(o);
// console.error(4);
// }).catch((err) => {
// console.error(5);
// console.error(err);
// });
if (devMode) {
Promise.longStackTraces();
}
// Bluebird uncaught error handler.
Promise.onPossiblyUnhandledRejection(function(err) {
console.log("onPossiblyUnhandledRejection");
if (_.isObject(err)) {
// since it may just throw as [object Object]
console.error(1);
console.dir(err);
console.error(2);
console.error(err);
console.error(3);
if (err && err.stack) {
console.error(err.stack);
}
try {
console.error(4);
console.error(JSON.stringify(err));
} catch (e) {
console.error(5);
console.error("stringify threw");
}
}
console.error(6);
// throw err; // not throwing since we're printing stack traces anyway
});
function requiredConfig(name) {
if (_.isUndefined(process.env[name])) {
throw "be sure to set the "+name+" environment variable";
}
}
requiredConfig("ADMIN_UIDS"); // for testing
requiredConfig("ADMIN_EMAILS"); // for notifying the team
requiredConfig("ADMIN_EMAIL_DATA_EXPORT"); // a "send as" address for data export
requiredConfig("ADMIN_EMAIL_DATA_EXPORT_TEST"); // for notifying of the outcome of automated data export testing
requiredConfig("ADMIN_EMAIL_EMAIL_TEST"); // for notifying of the outcome of email system testing
const admin_emails = JSON.parse(process.env.ADMIN_EMAILS);
const polisDevs = JSON.parse(process.env.ADMIN_UIDS);
function isPolisDev(uid) {
return polisDevs.indexOf(uid) >= 0;
}
// so we can grant extra days to users
// eventually we should probably move this to db.
// for now, use git blame to see when these were added
const usersToAdditionalTrialDays = {
50756: 14, // julien
85423: 100, // mike test
};
// log heap stats
setInterval(function() {
let mem = process.memoryUsage();
let heapUsed = mem.heapUsed;
let rss = mem.rss;
let heapTotal = mem.heapTotal;
winston.log("info", "heapUsed:", heapUsed, "heapTotal:", heapTotal, "rss:", rss);
// let start = Date.now();
//metric("api.process.mem.heapUsed", heapUsed, start);
//metric("api.process.mem.rss", rss, start);
//metric("api.process.mem.heapTotal", heapTotal, start);
}, 10 * 1000);
// // BEGIN GITHUB OAUTH2
// let CLIENT_SECRET = "0b178e412a10fa023a0153bf7cefaf6dae0f74b9";
// let CLIENT_ID = "109a1eb4732b3ec1075b";
// let oauth2 = require('simple-oauth2')({
// clientID: CLIENT_ID,
// clientSecret: CLIENT_SECRET,
// site: 'https://github.com/login',
// tokenPath: '/oauth/access_token'
// });
// winston.log("info",oauth2);
// // Authorization uri definition
// let authorization_uri = oauth2.AuthCode.authorizeURL({
// redirect_uri: 'https://preprod.pol.is/oauth2/oauth2_github_callback',
// scope: 'notifications',
// state: '3(#0/!~'
// });
// // END GITHUB OAUTH2
const POLIS_FROM_ADDRESS = process.env.POLIS_FROM_ADDRESS;
const akismet = akismetLib.client({
blog: 'https://pol.is', // required: your root level url
apiKey: process.env.AKISMET_ANTISPAM_API_KEY,
});
akismet.verifyKey(function(err, verified) {
if (verified) {
winston.log("info", 'Akismet: API key successfully verified.');
} else {
winston.log("info", 'Akismet: Unable to verify API key.');
}
});
// heroku pg standard plan has 120 connections
// plus a dev poller connection and a direct db connection
// 3 devs * (2 + 1 + 1) = 12 for devs
// plus the prod and preprod pollers = 14
// round up to 20
// so we can have 25 connections per server, of of which is the preprod server
// so we can have 1 preprod/3 prod servers, or 2 preprod / 2 prod.
if (devMode) {
pg.defaults.poolSize = 2;
} else {
pg.defaults.poolSize = 12;
}
// let SELF_HOSTNAME = "localhost:" + process.env.PORT;
// if (!devMode) {
// ^^^ possible to use localhost on Heroku?
// SELF_HOSTNAME = process.env.SERVICE_HOSTNAME
//}
// metric name => {
// values: [circular buffers of values (holds 1000 items)]
// index: index in circular buffer
//}
const METRICS_IN_RAM = {};
const SHOULD_ADD_METRICS_IN_RAM = false;
function addInRamMetric(metricName, val) {
if (!SHOULD_ADD_METRICS_IN_RAM) {
return;
}
if (!METRICS_IN_RAM[metricName]) {
METRICS_IN_RAM[metricName] = {
values: new Array(1000),
index: 0,
};
}
let index = METRICS_IN_RAM[metricName].index;
METRICS_IN_RAM[metricName].values[index] = val;
METRICS_IN_RAM[metricName].index = (index + 1) % 1000;
}
// metered promise
function MPromise(name, f) {
let p = new Promise(f);
let start = Date.now();
setTimeout(function() {
addInRamMetric(name + ".go", 1, start);
}, 100);
p.then(function() {
let end = Date.now();
let duration = end - start;
setTimeout(function() {
addInRamMetric(name + ".ok", duration, end);
}, 100);
}, function() {
let end = Date.now();
let duration = end - start;
setTimeout(function() {
addInRamMetric(name + ".fail", duration, end);
}, 100);
}).catch(function(err) {
let end = Date.now();
let duration = end - start;
setTimeout(function() {
addInRamMetric(name + ".fail", duration, end);
console.log("MPromise internal error");
}, 100);
});
return p;
}
function isSpam(o) {
return new MPromise("isSpam", function(resolve, reject) {
akismet.checkSpam(o, function(err, spam) {
if (err) {
reject(err);
} else {
resolve(spam);
}
});
});
}
var INFO;
if (devMode) {
INFO = console.log;
// INFO = function() {
// winston.log.apply(console, arguments);
// };
} else {
INFO = function() {};
}
// basic defaultdict implementation
function DD(f) {
this.m = {};
this.f = f;
}
// basic defaultarray implementation
function DA(f) {
this.m = [];
this.f = f;
}
DD.prototype.g = DA.prototype.g = function(k) {
if (this.m.hasOwnProperty(k)) {
return this.m[k];
}
let v = this.f(k);
this.m[k] = v;
return v;
};
DD.prototype.s = DA.prototype.s = function(k, v) {
this.m[k] = v;
};
// function emptyArray() {
// return [];
// }
const domainOverride = process.env.DOMAIN_OVERRIDE || null;
function haltOnTimeout(req, res, next) {
if (req.timedout) {
fail(res, 500, "polis_err_timeout_misc");
} else {
next();
}
}
function ifDefinedSet(name, source, dest) {
if (!_.isUndefined(source[name])) {
dest[name] = source[name];
}
}
//metric("api.process.launch", 1);
const errorNotifications = (function() {
let errors = [];
function sendAll() {
if (errors.length === 0) {
return;
}
// pushoverInstance.send({
// title: "err",
// message: _.uniq(errors).join("\n"),
// }, function(err, result) {
// winston.log("info","pushover " + err?"failed":"ok");
// winston.log("info",err);
// winston.log("info",result);
// });
errors = [];
}
setInterval(sendAll, 60 * 1000);
return {
add: function(token) {
if (devMode && !_.isString(token)) {
throw new Error("empty token for pushover");
}
console.error(token);
errors.push(token);
},
};
}());
const yell = errorNotifications.add;
const intercom = new Intercom({
apiKey: process.env.INTERCOM_API_KEY,
appId: "nb5hla8s",
});
//first we define our tables
const sql_conversations = sql.define({
name: 'conversations',
columns: [
"zid",
"topic",
"description",
"participant_count",
"is_anon",
"is_active",
"is_draft",
"is_public", // TODO remove this column
"is_data_open",
"is_slack",
"profanity_filter",
"spam_filter",
"strict_moderation",
"email_domain",
"owner",
"org_id",
"owner_sees_participation_stats",
"context",
"course_id",
"lti_users_only",
"modified",
"created",
"link_url",
"parent_url",
"vis_type",
"write_type",
"help_type",
"socialbtn_type",
"subscribe_type",
"bgcolor",
"help_color",
"help_bgcolor",
"style_btn",
"auth_needed_to_vote",
"auth_needed_to_write",
"auth_opt_fb",
"auth_opt_tw",
"auth_opt_allow_3rdparty",
],
});
// const sql_votes = sql.define({
// name: 'votes',
// columns: [
// "zid",
// "tid",
// "pid",
// "created",
// "vote",
// ],
// });
const sql_votes_latest_unique = sql.define({
name: 'votes_latest_unique',
columns: [
"zid",
"tid",
"pid",
"modified",
"vote",
],
});
const sql_comments = sql.define({
name: 'comments',
columns: [
"tid",
"zid",
"pid",
"uid",
"created",
"txt",
"velocity",
"active",
"mod",
"quote_src_url",
"anon",
],
});
const sql_participant_metadata_answers = sql.define({
name: 'participant_metadata_answers',
columns: [
"pmaid",
"pmqid",
"zid",
"value",
"alive",
],
});
const sql_participants_extended = sql.define({
name: 'participants_extended',
columns: [
"uid",
"zid",
"referrer",
"parent_url",
"created",
"modified",
"show_translation_activated",
"permanent_cookie",
"origin",
"encrypted_ip_address",
"encrypted_x_forwarded_for",
],
});
//first we define our tables
const sql_users = sql.define({
name: 'users',
columns: [
"uid",
"hname",
"email",
"created",
],
});
const sql_reports = sql.define({
name: 'reports',
columns: [
"rid",
"report_id",
"zid",
"created",
"modified",
"report_name",
"label_x_neg",
"label_x_pos",
"label_y_neg",
"label_y_pos",
"label_group_0",
"label_group_1",
"label_group_2",
"label_group_3",
"label_group_4",
"label_group_5",
"label_group_6",
"label_group_7",
"label_group_8",
"label_group_9",
],
});
// // Eventually, the plan is to support a larger number-space by using some lowercase letters.
// // Waiting to implement that since there's cognitive overhead with mapping the IDs to/from
// // letters/numbers.
// // Just using digits [2-9] to start with. Omitting 0 and 1 since they can be confused with
// // letters once we start using letters.
// // This should give us roughly 8^8 = 16777216 conversations before we have to add letters.
// let ReadableIds = (function() {
// function rand(a) {
// return _.random(a.length);
// }
// // no 1 (looks like l)
// // no 0 (looks like 0)
// let numbers8 = "23456789".split("");
// // should fit within 32 bits
// function generateConversationId() {
// return [
// rand(numbers8),
// rand(numbers8),
// rand(numbers8),
// rand(numbers8),
// rand(numbers8),
// rand(numbers8),
// rand(numbers8),
// rand(numbers8)
// ].join('');
// }
// return {
// generateConversationId: generateConversationId,
// };
// }());
function encrypt(text) {
const algorithm = 'aes-256-ctr';
const password = process.env.ENCRYPTION_PASSWORD_00001;
const cipher = crypto.createCipher(algorithm, password);
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text) {
const algorithm = 'aes-256-ctr';
const password = process.env.ENCRYPTION_PASSWORD_00001;
const decipher = crypto.createDecipher(algorithm, password);
var dec = decipher.update(text,'hex','utf8');
dec += decipher.final('utf8');
return dec;
}
decrypt; // appease linter
function makeSessionToken() {
// These can probably be shortened at some point.
return crypto.randomBytes(32).toString('base64').replace(/[^A-Za-z0-9]/g, "").substr(0, 20);
}
// But we need to squeeze a bit more out of the db right now,
// and generally remove sources of uncertainty about what makes
// various queries slow. And having every single query talk to PG
// adds a lot of variability across the board.
const userTokenCache = new LruCache({
max: 9000,
});
function getUserInfoForSessionToken(sessionToken, res, cb) {
let cachedUid = userTokenCache.get(sessionToken);
if (cachedUid) {
cb(null, cachedUid);
return;
}
pgQuery("select uid from auth_tokens where token = ($1);", [sessionToken], function(err, results) {
if (err) {
console.error("token_fetch_error");
cb(500);
return;
}
if (!results || !results.rows || !results.rows.length) {
console.error("token_expired_or_missing");
cb(403);
return;
}
let uid = results.rows[0].uid;
userTokenCache.set(sessionToken, uid);
cb(null, uid);
});
}
function createPolisLtiToken(tool_consumer_instance_guid, lti_user_id) {
return ["xPolisLtiToken", tool_consumer_instance_guid, lti_user_id].join(":::");
}
function isPolisLtiToken(token) {
return token.match(/^xPolisLtiToken/);
}
function isPolisSlackTeamUserToken(token) {
return token.match(/^xPolisSlackTeamUserToken/);
}
// function sendSlackEvent(slack_team, o) {
// return pgQueryP("insert into slack_bot_events (slack_team, event) values ($1, $2);", [slack_team, o]);
// }
function sendSlackEvent(o) {
return pgQueryP("insert into slack_bot_events (event) values ($1);", [o]);
}
function parsePolisLtiToken(token) {
let parts = token.split(/:::/);
let o = {
// parts[0] === "xPolisLtiToken", don't need that
tool_consumer_instance_guid: parts[1],
lti_user_id: parts[2],
};
return o;
}
function getUserInfoForPolisLtiToken(token) {
let o = parsePolisLtiToken(token);
return pgQueryP("select uid from lti_users where tool_consumer_instance_guid = $1 and lti_user_id = $2", [
o.tool_consumer_instance_guid,
o.lti_user_id,
]).then(function(rows) {
return rows[0].uid;
});
}
function startSession(uid, cb) {
let token = makeSessionToken();
//winston.log("info",'startSession: token will be: ' + sessionToken);
winston.log("info", 'startSession');
pgQuery("insert into auth_tokens (uid, token, created) values ($1, $2, default);", [uid, token], function(err, repliesSetToken) {
if (err) {
cb(err);
return;
}
winston.log("info", 'startSession: token set.');
cb(null, token);
});
}
function endSession(sessionToken, cb) {
pgQuery("delete from auth_tokens where token = ($1);", [sessionToken], function(err, results) {
if (err) {
cb(err);
return;
}
cb(null);
});
}
function setupPwReset(uid, cb) {
function makePwResetToken() {
// These can probably be shortened at some point.
return crypto.randomBytes(140).toString('base64').replace(/[^A-Za-z0-9]/g, "").substr(0, 100);
}
let token = makePwResetToken();
pgQuery("insert into pwreset_tokens (uid, token, created) values ($1, $2, default);", [uid, token], function(errSetToken, repliesSetToken) {
if (errSetToken) {
cb(errSetToken);
return;
}
cb(null, token);
});
}
function getUidForPwResetToken(pwresettoken, cb) {
// TODO "and created > timestamp - x"
pgQuery("select uid from pwreset_tokens where token = ($1);", [pwresettoken], function(errGetToken, results) {
if (errGetToken) {
console.error("pwresettoken_fetch_error");
cb(500);
return;
}
if (!results || !results.rows || !results.rows.length) {
console.error("token_expired_or_missing");
cb(403);
return;
}
cb(null, {
uid: results.rows[0].uid,
});
});
}
function clearPwResetToken(pwresettoken, cb) {
pgQuery("delete from pwreset_tokens where token = ($1);", [pwresettoken], function(errDelToken, repliesSetToken) {
if (errDelToken) {
cb(errDelToken);
return;
}
cb(null);
});
}
// Same syntax as pg.client.query, but uses connection pool
// Also takes care of calling 'done'.
function pgQueryImpl() {
let args = arguments;
let queryString = args[0];
let params;
let callback;
if (_.isFunction(args[2])) {
params = args[1];
callback = args[2];
} else if (_.isFunction(args[1])) {
params = [];
callback = args[1];
} else {
throw "unexpected db query syntax";
}
pg.connect(this.pgConfig, function(err, client, done) {
if (err) {
callback(err);
// force the pool to destroy and remove a client by passing an instance of Error (or anything truthy, actually) to the done() callback
done(err);
yell("pg_connect_pool_fail");
return;
}
client.query(queryString, params, function(err) {
if (err) {
// force the pool to destroy and remove a client by passing an instance of Error (or anything truthy, actually) to the done() callback
done(err);
} else {
done();
}
callback.apply(this, arguments);
});
});
}
const usingReplica = process.env.DATABASE_URL !== process.env[process.env.DATABASE_FOR_READS_NAME];
const prodPoolSize = usingReplica ? 3 : 12; /// 39
const pgPoolLevelRanks = ["info", "verbose"]; // TODO investigate
const pgPoolLoggingLevel = -1; // -1 to get anything more important than info and verbose. // pgPoolLevelRanks.indexOf("info");
const queryReadWriteObj = {
isReadOnly: false,
pgConfig: Object.assign(parsePgConnectionString(process.env.DATABASE_URL), {
poolSize: (devMode ? 2 : prodPoolSize),
// poolIdleTimeout: 30000, // max milliseconds a client can go unused before it is removed from the pool and destroyed
// reapIntervalMillis: 1000, //frequeny to check for idle clients within the client pool
poolLog: function(str, level) {
if (pgPoolLevelRanks.indexOf(level) <= pgPoolLoggingLevel) {
console.log("pool.primary." + level + " " + str);
}
},
}),
};
const queryReadOnlyObj = {
isReadOnly: true,
pgConfig: Object.assign(parsePgConnectionString(process.env[process.env.DATABASE_FOR_READS_NAME]), {
poolSize: (devMode ? 2 : prodPoolSize),
// poolIdleTimeout: 30000, // max milliseconds a client can go unused before it is removed from the pool and destroyed
// reapIntervalMillis: 1000, //frequeny to check for idle clients within the client pool
poolLog: function(str, level) {
if (pgPoolLevelRanks.indexOf(level) <= pgPoolLoggingLevel) {
console.log("pool.replica." + level + " " + str);
}
},
}),
};
function pgQuery() {
return pgQueryImpl.apply(queryReadWriteObj, arguments);
}
function pgQuery_readOnly() {
return pgQueryImpl.apply(queryReadOnlyObj, arguments);
}
function pgQueryP_impl(queryString, params) {
if (!_.isString(queryString)) {
return Promise.reject("query_was_not_string");
}
let f = this.isReadOnly ? pgQuery_readOnly : pgQuery;
return new Promise(function(resolve, reject) {
f(queryString, params, function(err, result) {
if (err) {
return reject(err);
}
if (!result || !result.rows) {
// caller is responsible for testing if there are results
return resolve([]);
}
resolve(result.rows);
});
});
}
function pgQueryP(queryString, params) {
return pgQueryP_impl.apply(queryReadWriteObj, arguments);
}
function pgQueryP_readOnly(queryString, params) {
return pgQueryP_impl.apply(queryReadOnlyObj, arguments);
}
function pgQueryP_readOnly_wRetryIfEmpty(queryString, params) {
return pgQueryP_impl.apply(queryReadOnlyObj, arguments).then(function(rows) {
if (!rows.length) {
// the replica DB didn't have it (yet?) so try the master.
return pgQueryP(queryString, params);
}
return rows;
}); // NOTE: this does not retry in case of errors. Not sure what's best in that case.
}
function pgQueryP_metered_impl(name, queryString, params) {
let f = this.isReadOnly ? pgQueryP_readOnly : pgQueryP;
if (_.isUndefined(name) || _.isUndefined(queryString) || _.isUndefined(params)) {
throw new Error("polis_err_pgQueryP_metered_impl missing params");
}
return new MPromise(name, function(resolve, reject) {
f(queryString, params).then(resolve, reject);
});
}
function pgQueryP_metered(name, queryString, params) {
return pgQueryP_metered_impl.apply(queryReadWriteObj, arguments);
}
function pgQueryP_metered_readOnly(name, queryString, params) {
return pgQueryP_metered_impl.apply(queryReadOnlyObj, arguments);
}
function hasAuthToken(req) {
return !!req.cookies[COOKIES.TOKEN];
}
function getUidForApiKey(apikey) {
return pgQueryP_readOnly_wRetryIfEmpty("select uid from apikeysndvweifu WHERE apikey = ($1);", [apikey]);
}
// http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side
function doApiKeyBasicAuth(assigner, header, isOptional, req, res, next) {
let token = header.split(/\s+/).pop() || '', // and the encoded auth token
auth = new Buffer(token, 'base64').toString(), // convert from base64
parts = auth.split(/:/), // split on colon
username = parts[0],
// password = parts[1], // we don't use the password part (just use "apikey:")
apikey = username;
return doApiKeyAuth(assigner, apikey, isOptional, req, res, next);
}
function doApiKeyAuth(assigner, apikey, isOptional, req, res, next) {
getUidForApiKey(apikey).then(function(rows) {
if (!rows || !rows.length) {
res.status(403);
next("polis_err_auth_no_such_api_token");
return;
}
assigner(req, "uid", Number(rows[0].uid));
next();
}).catch(function(err) {
res.status(403);
console.error(err.stack);
next("polis_err_auth_no_such_api_token2");
});
}
// function getXidRecordByXidConversationId(xid, conversation_id) {
// return pgQueryP("select * from xids where xid = ($2) and owner = (select org_id from conversations where zid = (select zid from zinvites where zinvite = ($1)))", [zinvite, xid]);
// }
function createDummyUser() {
return new MPromise("createDummyUser", function(resolve, reject) {
pgQuery("INSERT INTO users (created) VALUES (default) RETURNING uid;", [], function(err, results) {
if (err || !results || !results.rows || !results.rows.length) {
console.error(err);
reject(new Error("polis_err_create_empty_user"));
return;
}
resolve(results.rows[0].uid);
});
});
}
function createXidRecord(ownerUid, uid, xid, x_profile_image_url, x_name, x_email) {
return pgQueryP("insert into xids (owner, uid, xid, x_profile_image_url, x_name, x_email) values ($1, $2, $3, $4, $5, $6) " +
"on conflict (owner, xid) do nothing;", [
ownerUid,
uid,
xid,
x_profile_image_url || null,
x_name || null,
x_email || null,
]);
}
function getConversationInfo(zid) {
return new MPromise("getConversationInfo", function(resolve, reject) {
pgQuery("SELECT * FROM conversations WHERE zid = ($1);", [zid], function(err, result) {
if (err) {
reject(err);
} else {
resolve(result.rows[0]);
}
});
});
}
function getConversationInfoByConversationId(conversation_id) {
return new MPromise("getConversationInfoByConversationId", function(resolve, reject) {
pgQuery("SELECT * FROM conversations WHERE zid = (select zid from zinvites where zinvite = ($1));", [conversation_id], function(err, result) {
if (err) {
reject(err);
} else {
resolve(result.rows[0]);
}
});
});
}
function isXidWhitelisted(owner, xid) {
return pgQueryP("select * from xid_whitelist where owner = ($1) and xid = ($2);", [owner, xid]).then((rows) => {
return !!rows && rows.length > 0;
});
}
function getXidRecordByXidOwnerId(xid, owner, zid_optional, x_profile_image_url, x_name, x_email, createIfMissing) {
return pgQueryP("select * from xids where xid = ($1) and owner = ($2);", [xid, owner]).then(function(rows) {
if (!rows || !rows.length) {
console.log('no xInfo yet');
if (!createIfMissing) {
return null;
}
var shouldCreateXidEntryPromise = !zid_optional ? Promise.resolve(true) : getConversationInfo(zid_optional).then((conv) => {
return conv.use_xid_whitelist ? isXidWhitelisted(owner, xid) : Promise.resolve(true);
});
return shouldCreateXidEntryPromise.then((should) => {
if (!should) {
return null;
}
return createDummyUser().then((newUid) => {
console.log('created dummy');
return createXidRecord(owner, newUid, xid, x_profile_image_url||null, x_name||null, x_email||null).then(() => {
console.log('created xInfo');
return [{