-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
105 lines (95 loc) · 2.42 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
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const apiKey = process.env.SENDGRID_API_KEY || "secret";
const fetchLimit = parseInt(process.env.SENDGRID_FETCH_LIMIT) || 10
const app = express();
app.set("view engine", "pug");
const store = [];
const maxRequestBodySize = process.env.MAX_BODY_SIZE || "10mb";
app.use(
bodyParser.urlencoded({
extended: false,
limit: maxRequestBodySize
})
);
app.use(
bodyParser.json({
limit: maxRequestBodySize
})
);
app.use(
session({
secret: process.env.SESSION_COOKIE_SECRET || "secret",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: false,
maxage: 1000 * 60 * 30
}
})
);
app.get("/", function (req, res) {
if (!req.session.user) {
res.render("login");
return;
}
res.render("index", {
data: store
});
});
app.get("/json", function (req, res) {
const token = req.query.token;
if (token != apiKey) {
res.status(401).send("Unauthorized");
return;
}
res.send(store);
});
app.post("/", function (req, res) {
if (req.body.apikey != apiKey) {
res.render("login", {
error: "Failed login"
});
return;
}
req.session.user = { };
res.redirect(302, "/");
});
app.post("/v3/mail/send", function (req, res) {
// TODO: check auth
const { content, ...message } = req.body;
message.sent_at = Date.now();
const personalize = (message, substitutions) => {
return Object.keys(substitutions).reduce((value, key) => {
return value.split(key).join(substitutions[key]);
}, message)
}
const messages = message.personalizations.map(
({ substitutions = { }, ...personalization }) => {
return {
...message,
subject: personalize(personalization.subject || message.subject, substitutions),
content: content.map(c => {
if (!c.value) return c;
return {
...c,
// resolve substitutions
value: personalize(c.value, substitutions)
};
}),
personalizations: [personalization],
attachments: message?.attachments ??[]
};
}
);
store.unshift(...messages);
store.splice(fetchLimit);
res.status(202).end();
});
const port = process.env.PORT || 3030;
app.listen(port, function () {
console.log(`start app (port: ${port})`);
});