-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
302 lines (265 loc) · 8.96 KB
/
server.js
File metadata and controls
302 lines (265 loc) · 8.96 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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var https = require('https');
var http = require('http');
var fs = require('fs');
var auth = require('basic-auth');
var nodemailer = require('nodemailer');
var $ = jQuery = require('jquery');
require(process.cwd() + '/jquery.csv.min.js');
var Policy = require(process.cwd() + '/app/models/policy');
var mongoose = require('mongoose');
mongoose.connect('mongodb://cahl.berkeley.edu:1304/policies'); // ******put a /events after port to save into that db
var csvWeekly = '../MASTER_user_info.csv'; // change this to location of email csv
// var csvWeekly = '50_users.csv'; // change this to location of email csv
var csvDaily = '/deepedu/research/moocdrop/live-data/prediction.csv'; // change this to location of prediction csv
// var csvDaily = '/deepedu/research/moocdrop/live-data/moocdrop/50_pred.csv';
var secretUsername = 'UZVR050i5yGikbw'; // change: must be shared with cross_main.html
var secretPassword = 'y4x86hnRXUPLVMI'; // change: must be shared with cross_main.html
// making anonID to email dict
var index_csv = csvWeekly;
var anon_to_email = {};
var all_ids = [];
fs.readFile(index_csv, 'UTF-8', function(err, csv) {
$.csv.toArrays(csv, {}, function(err, data) {
for(var i=1, len=data.length; i<len; i++) {
if (data[i][3]) {
all_ids.push(data[i][1]);
anon_to_email[data[i][1]] = {'email': data[i][3]}; // email
if (data[i][4]) {
anon_to_email[data[i][1]].first = data[i][4]; // first name
}
if (data[i][5]) {
anon_to_email[data[i][1]].last = data[i][5]; // last name
}
}
else {
continue;
}
}
});
});
var masquerading = true;
var transporter;
var emailUsername;
var emailPassword;
if (masquerading) {
transporter = nodemailer.createTransport('smtps://' + 'postmaster@sandbox76804c9965674d70aa186801c11a401e.mailgun.org' + ':' + encodeURI('9443478548bc8bd3aba3d6debba802f6') + '@smtp.mailgun.org');
}
else {
emailUsername = 'email username here'; // change to the account you want to have sending emails
emailPassword = 'email password here';
transporter = nodemailer.createTransport('smtps://' + emailUsername + ':' + encodeURI(emailPassword) + '@smtp.email.com');
}
// These should exist on your server to use https
var pkey = fs.readFileSync('/etc/ssl/cahl.key').toString();
var pcert = fs.readFileSync('/etc/ssl/cahl.crt').toString();
var gd = [fs.readFileSync('/etc/ssl/gd_bundle.crt').toString()];
var options = {
key: pkey,
cert: pcert,
ca: gd
};
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// set our port
var port = process.env.PORT || 1337;
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Accept, X-CSRFToken, chap, seq, vert");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST");
next();
});
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
// middleware to use for all requests
router.use(function(req, res, next) {
next();
});
function checkCredentials(credentials) {
if (!credentials || credentials.name !== secretUsername || credentials.pass !== secretPassword) {
return false;
} else {
return true;
}
}
function myError(err) {
if (err) {
console.log(err);
console.log("email send failed");
}
}
// on routes that end in /email
// ----------------------------------------------------
router.route('/email')
.post(function(req, res) {
console.log(req.body.from === "");
if (req.body.pass === 'sadfvkn88asVLS891') {
var ids = req.body.ids;
if (req.body.ann === 'true') {
ids = all_ids;
}
if (ids) {
for (var j = 0; j < ids.length; j++) {
var id = ids[j];
if (id in anon_to_email) {
var message_body = req.body.body;
var source;
if (masquerading) {
source = req.body.reply;
}
else {
source = emailUsername;
}
var from = req.body.course + " Instructor" + " <" + source +">";
if (req.body.from) {
from = "'" + req.body.from + "'" + " <" + source +">";
}
if (anon_to_email[id].first) {
message_body = message_body.replace('[:firstname:]', anon_to_email[id].first);
}
else {
message_body = message_body.replace('[:firstname:]', '');
}
if (anon_to_email[id].first && anon_to_email[id].last) {
message_body = message_body.replace('[:fullname:]', anon_to_email[id].first + " " + anon_to_email[id].last);
}
else {
message_body = message_body.replace('[:fullname:]', '');
}
// if (req.body.from === "") {
// message_body += "\n\nPlease do not repond to this email.";
// }
sendEmail(anon_to_email[id].email, from, req.body.subject, message_body, req.body.reply, myError);
}
else {
continue;
}
}
}
res.send('sent');
}
else {
res.send('Access Denied');
res.end('Access denied');
}
});
function sendEmail(email, from, subject, content, reply, cb) {
var mailOptions = {
from: from, // sender name and address
to: email, // list of receivers
subject: subject, // subject line
text: content, // plaintext body
replyTo: reply //replyTo address
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error) {
cb(error);
}
cb(null);
});
}
// Sends the prediction file to the client
router.route('/predictions').get(function(req, res) {
var credentials = auth(req);
if (!checkCredentials(credentials)) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="cahl.berkeley.edu"');
res.end('Access denied');
return;
}
res.sendFile(csvDaily);
});
// Queries the database for just
router.route('/analytics').get(function(req, res) {
query = Policy.find({"analytics": "true" }).sort({"timestamp": -1});
query.exec(function (err, output) {
if (err) {
return next(err);
}
else {
res.json(output);
}
});
});
router.route('/all').get(function(req, res) {
query = Policy.find({"analytics": "false" }).sort({"timestamp" : -1});
query.exec(function (err, output) {
if (err) {
return next(err);
}
else {
res.json(output);
}
});
});
router.route('/save').post(function(req, res) {
var policy = new Policy();
if (req.body.analytics === 'true') {
if (req.body.ids) {
policy.ids = req.body.ids;
}
console.log(policy.ids);
policy.comp = req.body.comp;
policy.attr = req.body.attr;
policy.cert = req.body.cert;
policy.auto = req.body.auto;
}
else {
policy.ids = '';
policy.comp = [];
policy.attr = [];
policy.cert = [];
policy.auto = 'false';
}
policy.subject = req.body.subject;
policy.from = req.body.from;
policy.body = req.body.body;
policy.reply = req.body.reply;
policy.timestamp = req.body.timestamp;
policy.analytics = req.body.analytics;
policy.save(function(err) {
if (err) {
console.log("error when saving policy");
res.end();
return;
}
});
});
router.route('/changes').post(function(req, res) {
console.log("changes");
var p = {};
p.ids = req.body.ids;
p.from = req.body.from;
p.reply = req.body.reply;
p.subject = req.body.subject;
p.body = req.body.body;
p.comp = req.body.comp;
p.attr = req.body.attr;
p.cert = req.body.cert;
p.auto = req.body.auto;
Policy.update({"subject": req.body.old_subject}, {"$set": p}).exec();
res.json({ message: 'Successfully saved' });
});
// This route exists only for testing your password
router.route('/').get(function(req, res) {
var credentials = auth(req);
if (!checkCredentials(credentials)) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="cahl.berkeley.edu"');
res.end('Access denied');
return;
}
res.send("You logged in");
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
https.createServer(options, app).listen(port);
console.log('Node server start on port: ' + port);