-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmail-function.js
125 lines (122 loc) · 3.56 KB
/
gmail-function.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
const fli = require('fli-webtask');
const wt = require('webtask-tools');
const bodyParser = require('body-parser');
const express = fli.npm.express;
const request = fli.npm.request;
const as = fli.npm.async;
const _ = fli.npm.lodash;
const loader = fli.lib.loader;
const responseHandler = fli.lib.responseHandler;
const app = express();
const router = express.Router();
const {google} = require('googleapis');
const gmail = google.gmail('v1');
const validateMiddleware = (req, res, next) => {
if(req.webtaskContext.secrets.token !== req.query.token) {
const errMsgToken = 'No token.';
responseHandler(errMsgToken, res);
return next(errMsgToken);
}
const to = _.get(req, 'query.to') || _.get(req, 'body.to');
const subject = _.get(req, 'query.subject') || _.get(req, 'body.subject');
const body = _.get(req, 'query.body') || _.get(req, 'body.body');
if(!(to && subject && body)) {
const errMsgMail = 'No mail params provided: to, subject, body.';
responseHandler(errMsgMail, res);
return next(errMsgMail);
}
req.mailParams = {
from: req.webtaskContext.secrets.from,
to: to,
subject: subject,
body: body
};
return next();
};
const refreshToken = (context, cb) => {
as.waterfall([
(next) => request.post({
url: context.secrets.googleAuthUrl,
form: {
grant_type: 'refresh_token',
client_id: context.secrets.client_id,
client_secret: context.secrets.client_secret,
refresh_token: context.secrets.refresh_token
}
}, (err, httpResponse, body) => next(null, JSON.parse(body))),
(data, next) => {
var token = {
access_token: _.get(data, 'access_token'),
expire: Date.now() + 1000 * (_.get(data, 'expires_in', 0) - 60)
};
context.storage.set(token, () => next(null, token.access_token));
}
], cb);
};
const auth = (context, cb) => {
as.waterfall([
(next) => context.storage.get(next),
(storage, next) => {
if (Date.now() < _.get(storage, 'expire', 0)) {
return next(null, _.get(storage, 'access_token'));
}
return refreshToken(context, next);
}
], (err, access_token) => {
if(!!err) {
return cb(err);
}
var authObj = new google.auth.OAuth2();
authObj.setCredentials({
client_id: context.secrets.client_id,
client_secret: context.secrets.client_secret,
access_token: access_token,
refresh_token: context.secrets.refresh_token
});
return cb(null, authObj);
});
};
const generateMail = (m) => {
const messageParts = [
`From: <${m.from}>`,
`To: <${m.to}>`,
'Content-Type: text/html; charset=utf-8',
'MIME-Version: 1.0',
`Subject: ${m.subject}`,
'',
`${m.body}`
];
const message = messageParts.join('\n');
const encodedMessage = Buffer.from(message)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
return encodedMessage;
};
router
.all('/send', function (req, res) {
console.log(`-- google gmail published`);
as.waterfall([
(next) => auth(req.webtaskContext, next),
(authObj, next) => {
gmail.users.messages.send({
auth: authObj,
userId: 'me',
clientId: req.webtaskContext.secrets.client_id,
requestBody: {
raw: generateMail(req.mailParams)
}
})
.then(data => next(null, data))
.catch(err => next(null, err));
}
],
(err, response) => {
responseHandler(err, res, _.get(response, 'data'));
});
});
app
.use(bodyParser.json())
.use('/', validateMiddleware, router);
module.exports = wt.fromExpress(app);