-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
308 lines (299 loc) · 10.2 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
// Generated by LiveScript 1.5.0
(function(){
var fs, util, getsecret, koa, koaStatic, koaRouter, koaLogger, glob, on_heroku, selfSignedHttps, debounce, ref$, cfy, yfy, add_noerr, kapp, app, bodyParser, session, passport, SUSamlStrategy, saml, auth, memoizeSingleAsync, sleep, to_dict_list, get_sheet, get_spreadsheet_real, get_spreadsheet, get_seminars_attended_by_user, list_all_users, index_contents, serve_static, i$, len$, port;
fs = require('fs');
getsecret = require('getsecret');
koa = require('koa');
koaStatic = require('koa-static');
koaRouter = require('koa-router');
koaLogger = require('koa-logger');
glob = require('glob');
getsecret = require('getsecret');
on_heroku = process.env.PORT != null;
if (!on_heroku) {
selfSignedHttps = require('self-signed-https');
}
const { GoogleSpreadsheet } = require('google-spreadsheet');
const { promisify } = require('util')
//GoogleSpreadsheet = require('google-spreadsheet');
debounce = require('promise-debounce');
ref$ = require('cfy'), cfy = ref$.cfy, yfy = ref$.yfy, add_noerr = ref$.add_noerr;
kapp = koa();
kapp.use(koaLogger());
app = koaRouter();
bodyParser = require('koa-bodyparser');
kapp.use(bodyParser({
extendTypes: {
json: ['json', '**/json']
}
}));
session = require('koa-generic-session');
kapp.keys = [getsecret('session_keys')];
kapp.use(session({
key: 'test.cookie'
}));
passport = require('koa-passport');
kapp.use(passport.initialize());
kapp.use(passport.session());
SUSamlStrategy = require('passport-stanford').Strategy;
saml = new SUSamlStrategy({
protocol: 'https://',
idp: 'prod',
entityId: 'https://cs547check.herokuapp.com/',
loginPath: '/login',
path: '/saml/consume',
passReqToCallback: true,
passport: passport,
decryptionPvk: getsecret('sp_key'),
decryptionCert: getsecret('sp_cert'),
host: 'cs547check.herokuapp.com'
});
passport.use(saml);
passport.serializeUser(function(user, done){
return done(null, user);
});
passport.deserializeUser(function(user, done){
return done(null, user);
});
app.post('/saml/consume', passport.authenticate(saml.name, {
failureRedirect: '/',
failureFlash: true
}), function*(){
return this.redirect('/');
});
app.get('/login', passport.authenticate(saml.name, {
successRedirect: '/',
failureRedirect: '/login'
}));
app.get('/metadata', function*(){
this.type = 'application/xml';
this.status = 200;
return this.body = saml.generateServiceProviderMetadata(getsecret('sp_cert'));
});
auth = function*(next){
if (this.isAuthenticated()) {
return (yield next);
} else {
return this.redirect('/login');
}
};
app.get('/secret', auth, function*(){
console.log(this.req.user);
console.log(this.req.user.primary_email);
return this.body = 'secret stuff';
});
memoizeSingleAsync = function(func){
var debounced_func, cached_val;
debounced_func = debounce(yfy(func));
cached_val = null;
return cfy(function*(){
var result;
if (cached_val != null) {
return cached_val;
}
result = (yield debounced_func());
cached_val = result;
return result;
});
};
sleep = cfy(function*(time){
var sleep_base;
sleep_base = function(msecs, callback){
return setTimeout(callback, msecs);
};
return (yield yfy(sleep_base)(time));
});
to_dict_list = function(cells){
var output, header_cells, body_cells, col_to_name, i$, len$, item, row_idx_to_contents, idx, name, value;
output = [];
header_cells = cells.filter(function(x){
return x.row === 1;
});
body_cells = cells.filter(function(x){
return x.row !== 1;
});
col_to_name = {};
for (i$ = 0, len$ = header_cells.length; i$ < len$; ++i$) {
item = header_cells[i$];
col_to_name[item.col] = item.value;
}
row_idx_to_contents = [];
for (i$ = 0, len$ = body_cells.length; i$ < len$; ++i$) {
item = body_cells[i$];
idx = item.row - 2;
name = col_to_name[item.col];
value = item.value;
if (row_idx_to_contents[idx] == null) {
row_idx_to_contents[idx] = {};
}
row_idx_to_contents[idx][name] = value;
}
return row_idx_to_contents;
};
const creds = JSON.parse(getsecret('google_service_account'));
const doc = new GoogleSpreadsheet(getsecret('spreadsheet_id'));
async function accessSpreadsheet() {
console.log("inside accessSpreadsheet");
await doc.useServiceAccountAuth({
client_email: creds.client_email,
private_key: creds.private_key,
});
await doc.loadInfo(); // loads document properties and worksheets
console.log(doc.title);
const sheet = doc.sheetsByIndex[0]; // or use doc.sheetsById[id]
console.log(sheet.title);
console.log(sheet.rowCount);
return Promise.resolve(sheet);
}
async function get_spreadsheet_real() {
var sheet, cells;
sheet = await accessSpreadsheet();
rows = await sheet.getRows();
return Promise.resolve(rows);
};
get_spreadsheet = null;
(function(){
var last_time_fetched, cached_spreadsheet_results;
last_time_fetched = 0;
cached_spreadsheet_results = null;
return get_spreadsheet = cfy(function*(){
var current_time;
current_time = Date.now();
if (Math.abs(current_time - last_time_fetched) < 30000) {
return cached_spreadsheet_results;
}
cached_spreadsheet_results = (yield get_spreadsheet_real());
last_time_fetched = current_time;
return cached_spreadsheet_results;
});
})();
get_seminars_attended_by_user = cfy(function*(sunetid){
var spreadsheet, output, output_set, i$, len$, line, cur_sunetid, seminar;
sunetid = sunetid.trim().toLowerCase();
spreadsheet = (yield get_spreadsheet());
output = [];
output_set = {};
for (i$ = 0, len$ = spreadsheet.length; i$ < len$; ++i$) {
line = spreadsheet[i$];
cur_sunetid = line['SUNet ID'];
if (cur_sunetid == null) {
continue;
}
if (cur_sunetid.trim().toLowerCase() !== sunetid) {
continue;
}
seminar = line['Which seminar are you currently attending?'];
if (output_set[seminar] != null) {
continue;
}
// If no longer keeping track of live/non-live attendance, comment out the following block
attendance_status = line['Attendance:'];
attendance_string = '';
if (attendance_status == 'I certify by the Stanford Honor Code that I watched the entire seminar *non-live* (up to 2 per quarter, unless you are an SCPD student or in a timezone that makes live attendance infeasible with email exemption from staff)') {
attendance_string = '-- watched asynchronously';
}
else if (attendance_status == 'I certify by the Stanford Honor Code that I attended the entire seminar *live in person*') {
attendance_string = '-- attended live in person';
}
else {
attendance_string = '-- attended live on Zoom';
}
// End of block.
output_set[seminar] = true;
output.push(seminar.concat(" ", attendance_string));
}
return output;
});
list_all_users = cfy(function*(){
var spreadsheet, output, output_set, i$, len$, line, sunetid;
spreadsheet = (yield get_spreadsheet());
output = [];
output_set = {};
for (i$ = 0, len$ = spreadsheet.length; i$ < len$; ++i$) {
line = spreadsheet[i$];
sunetid = line['SUNet ID'].trim().toLowerCase();
if (output_set[sunetid] != null) {
continue;
}
output.push(sunetid);
output_set[sunetid] = true;
}
output.sort();
return output;
});
app.get('/attendance', auth, function*(){
var sunetid, seminars;
sunetid = this.request.query.sunetid;
console.log("this request is for");
console.log(sunetid);
if (sunetid == null) {
this.body = JSON.stringify([]);
return;
}
seminars = (yield get_seminars_attended_by_user(sunetid));
console.log("seminars: ");
console.log(seminars);
return this.body = JSON.stringify(seminars);
});
app.get('/pass_nopass', auth, function*(){
var output, all_users, i$, len$, user, seminars_attended, passed;
output = [];
all_users = (yield list_all_users());
for (i$ = 0, len$ = all_users.length; i$ < len$; ++i$) {
user = all_users[i$];
seminars_attended = (yield get_seminars_attended_by_user(user));
passed = seminars_attended.length >= 9;
output.push(user + ": " + passed);
}
return this.body = output.join('\n');
});
app.get('/nopass', auth, function*(){
var output, all_users, i$, len$, user, seminars_attended, passed;
output = [];
all_users = (yield list_all_users());
for (i$ = 0, len$ = all_users.length; i$ < len$; ++i$) {
user = all_users[i$];
seminars_attended = (yield get_seminars_attended_by_user(user));
passed = seminars_attended.length >= 9;
if (!passed) {
output.push(user + "");
}
}
return this.body = output.join('\n');
});
index_contents = fs.readFileSync('www/index.html', 'utf-8');
serve_static = koaStatic(__dirname + '/www');
for (i$ = 0, len$ = (ref$ = glob.sync('www/**')).length; i$ < len$; ++i$) {
(fn$.call(this, ref$[i$]));
}
app.get('/', auth, function*(){
var email, ref$, index_with_login;
email = (ref$ = this.req.user.primary_email) != null
? ref$
: (ref$ = this.req.user.email) != null
? ref$
: this.req.user.mail;
index_with_login = index_contents.replace('SOME_USERNAME_GOES_HERE', email);
return this.body = index_with_login;
});
kapp.use(app.middleware());
port = (ref$ = process.env.PORT) != null ? ref$ : 5000;
if (on_heroku) {
kapp.listen(port);
console.log("on heroku, listening to port " + port + " visit http://localhost:" + port);
} else {
selfSignedHttps(kapp.callback()).listen(5000, '0.0.0.0');
console.log("running locally, listening to port " + port + " visit https://localhost:" + port);
}
function fn$(filepath){
var fileroute;
fileroute = filepath.replace('www', '');
if (fileroute === '') {
return;
}
if (fileroute === '/index.html') {
return;
}
app.get(fileroute, auth, serve_static);
}
}).call(this);