-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
259 lines (223 loc) · 6.55 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
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var passport = require("passport");
var ensureLoggedIn = require("connect-ensure-login").ensureLoggedIn;
var flash = require("connect-flash");
var apiRouter = express.Router();
var uiRouter = express.Router();
const { nanoid } = require('nanoid');
const KEYLENGTH = 20;
const expressSession = require('express-session')({
secret: 'secret',
resave: false,
saveUninitialized: false
});
var authRouter = require("./routes/auth")
var db = require("./db/datastore")();
var exphbs = require("express-handlebars");
require('./boot/auth')();
require('./boot/initdb')();
const SMTPServer = require("smtp-server").SMTPServer;
const simpleParser = require("mailparser").simpleParser;
const authdb = require("./db/authdb");
const auth = require("./boot/auth");
const e = require("connect-flash");
var AUTH_ENABLED = false
authdb.all("SELECT * FROM users", (error, rows) => {
// If there are users provisioned, then enable authentication.
AUTH_ENABLED = rows.length > 0 ? true : false;
});
var app = express();
// view engine setup
app.engine(
"hbs",
exphbs({
extname: "hbs",
defaultLayout: "mainlayout",
layoutsDir: path.join(__dirname, "views"),
})
);
app.use(expressSession);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req, res, next) {
var msgs = req.session.messages || [];
res.locals.messages = msgs;
res.locals.hasMessages = !! msgs.length;
req.session.messages = [];
next();
});
app.set("view engine", "hbs");
app.set("views", path.join(__dirname, "views"));
// Import data store and get handle to db
dbHandle = db.getStore("updated_emailstore");
// create mail server
const server = new SMTPServer({
authOptional: true,
allowInsecureAuth: true,
maxAllowedUnauthenticatedCommands: 1000,
onConnect(session, callback) {
return callback();
},
onMailFrom(address, session, cb) {
cb();
},
onData(stream, session, callback) {
parseEmail(stream).then((mail) => {
db.insertEmail(mail);
callback();
}, callback);
},
});
function parseEmail(stream) {
return simpleParser(stream).then((email) => {
return email;
});
}
server.listen(25);
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
function buildPredicate(query) {
let predicate = Object.assign({}, query);
//delete to and cc as we have to process them separately
delete predicate["to"];
delete predicate["cc"];
if (query.cc) {
predicate["cc.value"] = { $elemMatch: { address: query.cc } };
}
if (query.to) {
predicate["to.value"] = { $elemMatch: { address: query.to } };
}
return predicate;
}
// Define API middleware
apiRouter.use(verifyToken);
// API Handlers starts with /api
apiRouter.use("/find", (req, res) => {
let predicate = buildPredicate(req.query);
db.findEmail(predicate).exec((error, docs) => {
res.json(docs);
});
});
apiRouter.use("/inbox", (req, response) => {
db.getInbox().exec((error, docs) => {
response.json(docs);
});
});
apiRouter.use("/purge", (req, response) => {
let predicate = buildPredicate(req.query);
dbHandle.remove(predicate, { multi: true }, (err, numRemoved) => {
if (!err) {
response.json({ rows_removed: numRemoved });
} else {
response.json({ error: err });
}
});
});
function showControls(req) {
return AUTH_ENABLED ? (req.user ? true: false) : true;
}
//UI Handlers
uiRouter.use(validateLogin("/login"));
uiRouter.get("/", function (req, res) {
res.render("mainlayout", { layout: false, showControls: showControls(req), user: req.user});
});
uiRouter.use("/inbox/", (req, response) => {
let predicate = buildPredicate(req.query);
db.getInbox(predicate).exec((error, docs) => {
response.render("mailbox", { layout: "mainlayout", docs: docs, showControls: showControls(req), user: req.user });
});
});
uiRouter.use("/details/:id", (req, response) => {
db.getInbox().exec((error, docs) => {
db.findEmail({ _id: req.params.id }).exec((err, result) => {
if (result[0].html) {
response.write(result[0].html);
} else {
response.write(
"<html><body>" + result[0].textAsHtml + "</body></html>"
);
}
response.end();
});
});
});
uiRouter.use("/user/preferences", (req, response) => {
authdb.serialize(function() {
authdb.get('SELECT * FROM users WHERE id = ?', [ req.user.id ], function(err, row) {
response.render("preferences", { layout: "mainlayout", user: req.user, accessToken: row.accessToken, showControls: showControls(req) });
});
});
});
uiRouter.use("/user/generatetoken", (req, response) => {
var accessToken = nanoid(KEYLENGTH);
authdb.serialize(() => {
authdb.run('UPDATE users SET accessToken = ? WHERE id = ?', [
accessToken,
req.user.id
], function(err) {
if (err) { console.log(err) };
});
});
response.json({accessToken: accessToken, userId: req.user.id});
});
app.use('/', authRouter);
app.use('/api', apiRouter);
app.use('/', uiRouter);
function validateLogin(options) {
if (typeof options == 'string') {
options = { redirectTo: options }
}
options = options || {};
var url = options.redirectTo || '/login';
var setReturnTo = (options.setReturnTo === undefined) ? true : options.setReturnTo;
return function(req, res, next) {
if (AUTH_ENABLED) {
if (!req.isAuthenticated || !req.isAuthenticated()) {
if (setReturnTo && req.session) {
req.session.returnTo = req.originalUrl || req.url;
}
return res.redirect(url);
}
next();
}
else{
next();
}
}
}
function verifyToken(req, res, next) {
if (AUTH_ENABLED) {
//If APIs are protected, enable authentication via token
const bearerHeader = req.headers['authorization'];
if (typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
authdb.serialize(function() {
authdb.get('SELECT * FROM users WHERE accessToken = ?', [ bearerToken ], function(err, row) {
if (row) {
req.token = bearerToken;
next();
}
else{
res.sendStatus(403);
}
});
});
}
else {
res.sendStatus(403);
}
}
else {
next();
}
}
module.exports = app;