This repository has been archived by the owner on Aug 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
220 lines (209 loc) · 7.62 KB
/
index.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
/**
* Original: Copyright 2018, Google LLC
* Modifications: Copyright 2024, Michael Daniels
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const logger = require('./lib/log').logger;
/**
* Request an OAuth 2.0 authorization code
* Only new users (or those who want to refresh
* their auth data) need visit this page
*/
exports.oauth2init = (_, res) => {
const oauth = require('./lib/oauth');
// Define OAuth2 scopes
const scopes = [
'https://www.googleapis.com/auth/gmail.readonly'
];
// Generate + redirect to OAuth2 consent form URL
const authUrl = oauth.client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
prompt: 'consent' // Required in order to receive a refresh token every time
});
logger.debug({ entry: 'authUrl: ' + authUrl });
return res.redirect(authUrl);
};
/**
* Get an access token from the authorization code and store token in Datastore
*/
exports.oauth2callback = (req, res) => {
const oauth = require('./lib/oauth');
const { google } = require('googleapis');
const gmail = google.gmail({ version: 'v1', auth: oauth.client });
const querystring = require('querystring');
// Get authorization code from request
const code = req.query.code;
// OAuth2: Exchange authorization code for access token
oauth.client.getToken(code)
.then((r) => {
oauth.client.setCredentials(r.tokens);
})
.then(() => {
// Get user email (to use as a Datastore key)
return gmail.users.getProfile({
auth: oauth.client,
userId: 'me'
});
})
.then((profile) => {
return profile.data.emailAddress;
})
.then((emailAddress) => {
// Store token in Datastore
return Promise.all([
emailAddress,
oauth.saveToken(emailAddress)
]);
})
.then(([emailAddress, _]) => {
// Respond to request
logger.info({ entry: 'Auth initialized for ' + emailAddress });
res.write('Successfully authenticated.' +
`Do you want to <a href="/setCron?emailAddress=${querystring.escape(emailAddress)}">set the cron job</a> or ` +
`<a href="/setEditQuery?emailAddress=${querystring.escape(emailAddress)}">set or edit your query</a>?`);
res.status(200).end();
})
.catch((err) => {
// Handle error
logger.error({ entry: JSON.stringify(err, null, 4) });
res.status(500).send('Something went wrong; check the logs.');
});
};
// This is not secure, but since only I have access to it it's OK.
// TODO: remove? Not worth effort.
/*
exports.setCron = (req, res) => {
const querystring = require('querystring');
const datastore = require('./lib/datastore').datastore;
const { CloudSchedulerClient } = require('@google-cloud/scheduler').v1;
const schedulerClient = new CloudSchedulerClient({
projectId: process.env.GCLOUD_PROJECT
});
// const { PubSub } = require('@google-cloud/pubsub');
// const pubsub = new PubSub({ projectId: process.env.GCLOUD_PROJECT });
// Require a valid email address
if (!req.query.emailAddress) {
return res.status(400).send('No emailAddress specified.');
}
const email = querystring.unescape(req.query.emailAddress);
if (!email.includes('@')) {
return res.status(400).send('Invalid emailAddress.');
}
const location = 'projects/' + process.env.GCLOUD_PROJECT + '/locations/' + process.env.GCF_REGION;
logger.debug({ entry: 'location: ' + location });
return schedulerClient.createJob({
parent: location,
job: {
description: 'gmail notifier for ' + email,
schedule: \'\*\/7 * * * *', // TODO: remove backslashes if uncommenting.
pubsubTarget: {
topicName: 'projects/' + process.env.GCLOUD_PROJECT + '/topics/gmail-notifier-' + email.substring(0, email.indexOf('@')),
data: {
emailAddress: email,
time: Date.now()
}
}
}
})
.then((job) => {
logger.debug({ entry: JSON.stringify(job, null, 4) });
return datastore.save({
key: datastore.key(['lastRunTime', email]),
data: {
lastRunTime: Date.now()
}
});
})
.then((datastoreResponse) => {
logger.debug({ entry: JSON.stringify(datastoreResponse, null, 4) });
// Respond with status
res.write('Cron initialized!');
res.status(200).end();
})
.catch((err) => {
// Handle errors
logger.error({ entry: JSON.stringify(err, null, 4) });
res.status(500).send('Something went wrong; check the logs.');
});
};
*/
// This is not secure, but since only I have access to it it's OK.
exports.setEditQuery = (req, res) => {
const querystring = require('querystring');
const { Datastore } = require('@google-cloud/datastore');
const datastore = new Datastore({ databaseId: 'gmail-notifier' });
if (req.method === 'GET') {
// Require a valid email address
if (!req.query.emailAddress) {
return res.status(400).send('No emailAddress specified.');
}
const email = querystring.unescape(req.query.emailAddress);
if (!email.includes('@')) {
return res.status(400).send('Invalid emailAddress.');
}
datastore.get(datastore.key(['query', email]))
.catch((err) => {
logger.warn({ entry: JSON.stringify(err, null, 4) });
return null;
})
.then((currentQueryObj) => {
logger.info({ entry: 'currentQueryObj is ' + JSON.stringify(currentQueryObj, null, 4) });
if (currentQueryObj == null) {
res.write('No query for ' + email + ' right now.<br>');
} else {
res.write('Current query for <code>' + email + '</code>: <code>' + currentQueryObj.query +
'</code> (last updated ' + currentQueryObj.queryLastUpdated + ')<br>');
}
res.write('<form action="/setEditQuery" method="post">' +
'<label for="query">Query:</label>' +
'<input type="text" id="query" name="query">' +
'<input type="hidden" id="emailAddress"' +
'name="emailAddress" value="' + email + '">' + '<br>' +
'<input type="submit" value="Submit">' +
'</form>'
);
res.status(200).end();
})
.catch((err) => {
// Handle errors
logger.error({ entry: JSON.stringify(err, null, 4) });
res.status(500).send('Something went wrong; check the logs.');
});
} else if (req.method === 'POST') {
logger.info({ entry: 'req.body: ' + JSON.stringify(req.body) });
const email = req.body.emailAddress;
datastore.save({
key: datastore.key(['query', email]),
data: {
query: req.body.query,
queryLastUpdated: Date.now()
}
})
.then((datastoreResponse) => {
logger.info({ entry: 'datastoreResponse: ' + JSON.stringify(datastoreResponse) });
res.write('Successfully saved query <code>' + req.body.query +
'</code> for <code>' + req.body.emailAddress + '</code>');
res.status(200).end();
})
.catch((err) => {
// Handle errors
logger.error({ entry: JSON.stringify(err, null, 4) });
res.status(500).send('Something went wrong; check the logs.');
});
} else {
res.status(405).send('Invalid method: only GET and POST allowed');
}
};