-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
400 lines (321 loc) · 11.4 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
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
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var config = require('./config');
var db = require('./database');
var request = require('request');
var auth = require('tent-auth');
var discover = require('tent-discover');
var tentRequest = require('tent-request');
var app = express();
//session store
var MongoStore = require('connect-mongo')(express);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(express.favicon());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
var sessionCreds = config.session();
var sessionServer = sessionCreds.server;
var sessionSecret = sessionCreds.secret;
app.use(express.session({
store: new MongoStore({
url: 'mongodb://' + sessionServer
}),
secret: sessionSecret
}));
app.use(app.router);
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
app.use(express.static(path.join(__dirname, 'public')));
// development vs prod
if ('development' == app.get('env')) {
app.use(express.errorHandler());
app.use(express.logger('dev'));
var tentAppConfig = {
name: 'Oatmail Dev App',
url: 'http://dragonstone-nodejs-56183.euw1.nitrousbox.com',
redirect_uri: 'http://dragonstone-nodejs-56183.euw1.nitrousbox.com/auth/callback/',
types: {
read: [ 'https://oatmail.io/types/email/v0', 'https://oatmail.io/types/emailMeta/v0' ],
write: [ 'https://oatmail.io/types/email/v0', 'https://oatmail.io/types/emailMeta/v0' ]
}
}
} else {
var tentAppConfig = {
name: 'Oatmail',
url: 'http://oatmail.io',
redirect_uri: 'http://oatmail.io/auth/callback/',
types: {
read: [ 'https://oatmail.io/types/email/v0', 'https://oatmail.io/types/emailMeta/v0' ],
write: [ 'https://oatmail.io/types/email/v0', 'https://oatmail.io/types/emailMeta/v0' ]
}
}
}
app.get('/', routes.index);
app.get('/mailbox/:folder', routes.mailbox);
app.get('/registration', routes.registration);
app.get('/view/:id', routes.view);
app.get('/compose', routes.compose);
//reply/replyall/forward
app.get('/compose/:type/:id', routes.compose);
app.post('/authenticate', function(req, res){
var entity = req.body.protocol + req.body.entity + req.body.tentHost;
//check entity begins in https:// or http://
var regex = /^https:|http:/
var result = regex.exec(entity);
if (!result) {
return res.json("error: tent address must start with https:// or http://")
}
//if the entity (user) already registered the app, skip the registration skip and directly obtain refreshed tokens ("login")
db.getTempAuthStoreByEntity(entity, function(store) {
if(store === "not found" || store === "failed auth found and removed") {
console.log("authenticating new user");
authenticateNewUser();
} else {
console.log("authenticating existing user");
authenticateExistingUser(store);
}
});
//existing user
var authenticateExistingUser = function(store) {
console.log('existing user %s', entity)
var url = auth.generateURL(store.meta.post.content, store.appID);
db.updateTempAuthStateByEntity(url.state, entity, function() {
res.redirect(url.url);
});
};
//new user
var authenticateNewUser = function() {
console.log('new user %s', entity)
var store = {};
// create a new temp auth store for this user
var tempAuthId = db.createTempAuth(entity, store);
discover(entity, function(err, meta) {
if(err) {
//entity not found
return res.send("entity not found, press the back key and try again");
}
store.meta = meta
// we have to clone the app object, to not modify the global one
var cTentAppConfig = JSON.parse(JSON.stringify(tentAppConfig))
// the callback needs to identify to whom the code belongs
cTentAppConfig.redirect_uri += tempAuthId
// register the app with the server
// this step is skipped the next time
auth.registerApp(meta.post.content, cTentAppConfig,
function(err, tempCreds, appID) {
if(err) return res.send(err)
store.appID = appID
// these temporary credentials, only used during authentication
store.tempCreds = tempCreds
//finally generate the auth url and direct the user there!
var url = auth.generateURL(meta.post.content, appID)
store.state = url.state
res.redirect(url.url)
//update the temp data store
db.updateTempAuthStoreById(tempAuthId,store);
})
})
}
});
// this resource is only called by the tent server
app.get('/auth/callback/:id', function(req, res) {
console.log('callback id %s', req.params.id)
// get the store corresponding to the id
db.getTempAuthStoreById(req.params.id, function(tAuth) {
// check state
var store = tAuth.store;
if(store.state !== req.query.state) {
return res.send('mismatching state') //it's an existing user?
} else if(req.query.error) {
return res.send('Error during auth, please try again or contact your tent provider');
} else {
var entityName = tAuth.entity;
// make the final request, to trade the code for permanent credentials
auth.tradeCode(store.meta.post.content, store.tempCreds, req.query.code,
function(err, permaCreds) {
if(err) {
console.log("err: " + err);
return res.send(err);
} else {
db.updateTempAuthStoreCredsByEntity(entityName, permaCreds, function() {
req.session.entityStore = tAuth;
req.session.entityStore.store.creds = permaCreds;
if(typeof(tAuth.email) !== 'undefined') {
console.log("log in successful, going to inbox!");
return res.redirect('/');
} else {
console.log("new user, let's get them a tentmail address!");
return res.redirect('/registration');
}
});
}
});
}
});
})
//form for adding an email address to a user's account, required at login
app.post('/registerEmail', function(req, res){
var email = req.body.email;
var entity = req.session.entityStore.entity;
db.checkEmailExists(email, function(doc) {
console.log("checking if email exists");
if(!doc) {
console.log("email not found");
//email not taken / found
db.updateEmailByEntity(entity, email, function(success){
if(success) {
console.log("added email to entity - I should switch this to a redis key/value in the next release!");
req.session.entityStore.email = email + '@oatmail.io';
sendWelcomeEmail(req.session.entityStore.email);
return res.redirect('/');
}
else {
return res.json("error adding email to entity");
}
})
}
else {
return res.json("error: email already registered to another user");
}
});
});
app.get("/logout", function(req, res) {
req.session.destroy();
return res.redirect('/');
});
/*API FUNCTIONS */
app.post("/api/recieve", function(req, res) {
var email = req.body,
allRecipients = email.to.concat(email.cc,email.bcc);
checkOatmailAddressExists(allRecipients, email, function(exists) {
if(exists) {
return res.send(200);
} else {
//none of the recipients are registered with oatmail.io
return res.send(404);
}
});
});
var checkOatmailAddressExists = function(allRecipients, email, callback) {
var addressFound = false;
for (var i = 0; i < allRecipients.length; i++) {
if(typeof(allRecipients[i]) !== 'undefined') {
var recipient = allRecipients[i].address;
db.checkEmailExists(recipient, function(doc) {
if(doc) {
//create the meta post for the app
var emailMeta = {};
emailMeta.direction = "incoming";
emailMeta.draft = false;
emailMeta.folder = "inbox";
addEmailToTent(email, emailMeta, doc.store.meta, doc.store.creds);
addressFound = true;
}
});
}
}
if (addressFound === true) {
return callback(true);
}
else {
return callback(false);
}
};
app.post('/api/sendEmail', function(req, res){
var email = req.body;
//need to check if a reply, attachments, validate the user input, anything else?
sendEmail(email, function(error, response, body) {
if(error) {
console.log(error);
return res.send(500);
}
var meta = req.session.entityStore.store.meta;
var creds = req.session.entityStore.store.creds;
//create the meta post for the app
var emailMeta = {};
emailMeta.direction = "outgoing";
emailMeta.draft = false;
emailMeta.folder = "sent";
addEmailToTent(email, emailMeta, meta, creds);
return res.send(200);
})
});
var addEmailToTent = function (email, emailMeta, meta, creds) {
//dump the request into tent entity address
var tentClient = tentRequest(meta, creds);
console.log("storing email with subject: " + email.subject);
tentClient.create('https://oatmail.io/types/email/v0#',
{ permissions: false },
email,
function(err, resonse, body) {
if(!err) {
//this needs fixing at 0.4 to a link
emailMeta.ref = body.id;
tentClient.create('https://oatmail.io/types/emailMeta/v0#',
{ permissions: false },
emailMeta,
function(err, response, body) {
if(!err) {
return 200;
} else {
console.log(err);
}
}
);
} else {
console.log(err);
}
}
);
}
var sendEmail = function(email, callback) {
var reqOptions = {
url: 'http://107.170.4.31:3000/smtp/send',
method: "POST",
body: email,
json: true,
strictSSL: false
}
request(reqOptions, function(error, response, body) {
callback(error, response, body);
});
}
//this is called when a new user registers their email address
var sendWelcomeEmail = function(emailAddress) {
var email = {};
email.to = emailAddress;
email.from = "[email protected]";
email.subject = "Welcome to Oatmail!";
email.html = "Thanks for signing up, if you have any questions, issues or ideas reply back to this oatmail or contact me at ^pauljohncleary.cupcake.is"
email["stripped-text"] = email.html;
sendEmail(email, function(error, response, body) {});
}
app.post('/api/deleteEmail', function(req, res){
var id = req.body.id;
var meta = req.session.entityStore.store.meta;
var creds = req.session.entityStore.store.creds;
var tentClient = tentRequest(meta, creds);
tentClient.delete(id, function(error, response, body) {
if(error) {
console.log(error);
}
else {
return res.send(response.statusCode);
}
});
});
/** END OF API **/
//check db is connected
db.checkDB();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});