-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsendgrid.js
75 lines (69 loc) · 1.98 KB
/
sendgrid.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
// using Twilio SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const sgMail = require('@sendgrid/mail');
const app = require('express').Router();
const axios = require('axios');
const _ = require('lodash');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// console.log('SENDGRID API KEY', process.env.SENDGRID_API_KEY);
const auth = async (req, res, next) => {
console.log(req.headers);
let token = _.get(req, 'headers.authorization');
if (token.startsWith('Bearer ')) {
token = token.substring(7, token.length);
} else {
res.status(401).send({ message: 'Bearer Token: Incorrect Format' });
}
if (token) {
let result = null;
try {
result = await axios.post(
`https://preview.twilio.com/iam/Accounts/${
process.env.TWILIO_ACCOUNT_SID
}/Tokens/validate`,
{ token },
{
auth: {
username: process.env.TWILIO_ACCOUNT_SID,
password: process.env.TWILIO_AUTH_TOKEN,
},
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'application/json',
},
},
);
} catch (error) {
console.error('Error attempting to validate user token: ', error);
res.status(500).send({ message: "Couldn't reach authorization server." });
}
if (_.get(result, 'data.valid', false)) {
next();
} else {
_.set(result, 'data.tokenSent', token);
console.warn('Unauthorized Access to API', result.data);
res.status(401).send({ message: 'User is unauthorized' });
}
} else {
res.status(401).send({ message: 'No Auth Provided' });
}
};
app.post('/send', auth, (req, res) => {
console.log('SendGrid - Send Request: ', req.headers, req.body);
const {
to, from, subject, html
} = req.body;
const msg = {
to,
from,
subject,
html,
};
try {
sgMail.send(msg);
} catch (error) {
console.error(error);
}
res.sendStatus(204);
});
module.exports = app;