-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
128 lines (109 loc) · 4.33 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
const express = require('express');
const nodemailer = require('nodemailer');
const axios = require('axios');
const hbs = require('nodemailer-express-handlebars');
// load environment variables
require('dotenv').config();
const app = express();
// set the view engine
app.set('view engine', 'handlebars');
// define the port
const port = process.env.PORT || 3000;
// getting all the environment variables
const email = process.env.EMAIL;
const password = process.env.PASSWORD;
const serverUrl = process.env.SERVER_URL;
const emailHost = process.env.EMAIL_HOST;
const clientToken = process.env.CLIENT_TOKEN;
// custom constants
const subject = 'CyberManipal | The Tech News You Need';
let mailingList = "";
// custom list of greetings to pick randomly from
const greetingList = [
"Here's your weekly dose of byte sized cybersecurity news.",
"Wanna hear about the latest in tech? Read it on CyberManipal.",
"(sudo apt-get) update yourself with this handout of cybersecurity news.",
"If you are looking for tech news, look no further.",
"Glance through curated, informative news from the realms of technology."
]
// get route
app.get("/", (req, res) => {
res.status(200).send("<h4 style='font-family: sans-serif'>Wait for next Thursday for your newsletter</h4>");
});
// post route
app.post("/", async(req, res) => {
if(req.headers.auth_key === process.env.AUTH_KEY){
try {
// fetch the latest news to be hadned out
const resNews = await axios.get(`${serverUrl}/api/news?page=0`);
let latestFive = resNews.data.data.slice(0, 5);
// format the date field and the link field
latestFive.forEach(news => {
news.link = `https://cybermanipal.wearemist.in/article/${news._id}`
let tempDate = new Date(news.date);
news.date = tempDate.toDateString();
news.snippet = news.description.split(" ").slice(0, 70).join(" ");
})
// fetch the subscribers
const resEmails = await axios.get(`${serverUrl}/api/newsletter`, {
headers: {
"client_token" : clientToken
}
});
subscriberList = resEmails.data.data;
// create the mailing list
let tempList = [];
subscriberList.forEach(sub => {
tempList.push(sub.email)
});
mailingList = tempList.join(", ");
// create a transporter object
const transporter = nodemailer.createTransport({
host: emailHost, // configure to use your mail host
port: 465,
secure: true, // use SSL
auth: {
user: email,
pass: password,
},
});
// transporter options for hbs
var options = {
viewEngine : {
extname: '.hbs', // handlebars extension
layoutsDir: 'views/email/', // location of handlebars templates
defaultLayout: 'index', // name of main template
partialsDir: __dirname + 'views/email/partials/'
},
viewPath: 'views/email',
extName: '.hbs'
}
// apply hbs config
transporter.use('compile', hbs(options));
// defining all the email options
const messageOptions = {
from: email,
to: mailingList,
subject: subject,
template: 'index',
context: {
news: latestFive,
greeting: greetingList[Math.floor(Math.random() * greetingList.length)]
}
}
// send the email
transporter.sendMail(messageOptions, () => {
// optional callback here
});
console.log('Emails for ' + new Date().toISOString().slice(0, 10) + ' sent successfully');
res.status(200).send({ message: "Emails sent" });
} catch (e) {
console.log(e);
}
} else {
res.status(400).send({ message: "Auth error" });
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`)
});