-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifyaccount.js
346 lines (290 loc) · 9.89 KB
/
verifyaccount.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import config from 'config'
import FakeSelenium from './fakeselenium'
import imap from 'imap-simple'
import mysql from 'mysql'
import request from 'request-promise-native';
import {Builder, By, until} from 'selenium-webdriver';
import winston from 'winston'
const ACCOUNT_ACTIVATED = 'Your account is now active.'
const ACCOUNT_ALREADY_ACTIVATED = 'Your account has already been activated.'
const INVALID_CONFIRMATION_TOKEN = 'We cannot find an account matching the confirmation email.'
const VERIFICATION_EMAIL_SENT = 'We have sent you an email to verify your account.'
const RATE_LIMITING_ERROR = '403 Forbidden'
const UNHANDLED_ERROR = 'Unhandled error.'
const logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
timestamp: () => {
return Date.now()
},
formatter: (options) => {
return '['+ new Date(options.timestamp()).toISOString() +']['+ options.level.toUpperCase() +'] '+ (options.message ? options.message : '') +
(options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' )
},
level: config.get('verbosity'),
}),
],
})
const conn = {imap: config.get('imap')}
// Fallback to avoid errors, because simple-imap tries to modify this value,
// which is read-only if it come from the config.
conn.imap.authTimeout = config.get('imap.timeout')
const searchAccount = (conn, login) => {
return new Promise((resolve, reject) => {
conn.query({
sql: 'SELECT id FROM accounts WHERE login = ?',
values: [
login
]
}, (err, results) => {
if (err) {
return reject(err)
}
if (results.length == 0) {
return resolve(null)
} else {
return resolve(results[0].id)
}
})
})
}
const insertAccount = (conn, login, email) => {
return new Promise((resolve, reject) => {
logger.info(`Inserting account "${login}" into database.`)
const account = [
login, config.get('default_password'), email,
]
conn.query('INSERT INTO accounts(login, password, email) VALUES(?, ?, ?)', account, (err, result) => {
if (err) {
logger.error('Failed to query the database. Error: ' + err)
return reject(err)
}
return resolve(result.insertId)
})
})
}
const updateAccount = (conn, activated, id) => {
return new Promise((resolve, reject) => {
const d = new Date()
const updated_at = d.getFullYear()+"-"+d.getMonth()+"-"+d.getDay()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()
const account = [
activated, updated_at, id
]
conn.query('UPDATE accounts SET activated=?, updated_at=? WHERE id=?', account, (err, result, fields) => {
if (err) {
logger.error('Failed to query the database. Error: ' + err)
return reject(err)
}
return resolve(id)
})
})
}
const newRequest = (url) => {
return new Promise((resolve, reject) => {
if (config.get('request_type') == 'selenium') {
const driver = new Builder().forBrowser(config.get('webdriver')).build()
driver.get(url)
const t = 5 * 1000
driver.wait(until.elementLocated(By.id('sign-up-theme')), t).then(() => {
driver.getPageSource().then(body => {
resolve([body, driver])
}).catch(err => {
reject(err)
})
}).catch(err => {
driver.getTitle().then(title => {
if (title === RATE_LIMITING_ERROR) {
reject({statusCode: 503})
} else {
reject(err)
}
})
})
} else {
const req = request(url)
req.then(body => {
resolve([body, new FakeSelenium()])
}).catch(err => {
reject(err)
})
}
})
}
const requestNewValidationEmail = (driver, link, login, password) => {
return new Promise((resolve, reject) => {
const t = 5 * 1000
driver.wait(until.elementLocated(By.id('sign-up-theme')), t).then(() => {
logger.info(`Asking a new verification email for the account ${login}...`)
logger.debug(`Writing username...`)
const loginElm = driver.findElement(By.name('username'))
loginElm.sendKeys(login)
logger.debug(`Writing password...`)
const pwdElem = driver.findElement(By.name('password'))
pwdElem.sendKeys(password)
logger.debug(`Submiting form...`)
pwdElem.submit()
driver.wait(until.elementLocated(By.id('sign-up-theme')), t).then(() => {
driver.getPageSource().then(body => {
if (body.indexOf(VERIFICATION_EMAIL_SENT) >= 0) {
logger.info(`Success requesting the new verification email for the account ${login}!`)
driver.quit()
resolve()
}
})
}).catch(() => {
setTimeout(() => {
driver.get(link)
requestNewValidationEmail(driver, link, login, password).then(() => {
resolve()
})
}, 60000)
})
}).catch(() => {
requestNewValidationEmail(driver, link, login, password).then(() => {
resolve()
})
})
})
}
const validateAccount = (link, id, login, password) => {
return new Promise((resolve, reject) => {
newRequest(link).then(data => {
let body
let driver
[body, driver] = data
if (body.indexOf(ACCOUNT_ACTIVATED) >= 0) {
logger.info(`The account "${login}"(${id}) has been activated.`)
driver.quit()
resolve(['Y', id])
} else if (body.indexOf(ACCOUNT_ALREADY_ACTIVATED) >= 0) {
logger.info(`The account "${login}"(${id}) has already been activated.`)
driver.quit()
resolve(['Y', id])
} else if (body.indexOf(INVALID_CONFIRMATION_TOKEN) >= 0) {
logger.info(`The activation link for "${login}"(${id}) has already expired.`)
requestNewValidationEmail(driver, link, login, password).then(() => {
resolve(['N', id])
}).catch(err => {
reject(err)
})
}
}).catch(err => {
if (typeof err.statusCode !== undefined && err.statusCode === 503) {
logger.error(`Error 503 while activating the account "${id}". Waiting ~1min...`);
setTimeout(() => {
validateAccount(link, id, login, password).then(details => {
resolve(details)
})
}, 65000)
} else {
console.log(err)
process.exit(0)
}
})
})
}
const iterateOverMessages = (imap_connection, messages, mysql_connection) => {
logger.info(`There are ${messages.length} unread activation messages.`)
logger.debug('Reading each message...')
let counter = 0
const messagesPromises = messages.map(message => {
const messagePromise = new Promise((resolve, reject) => {
counter += 1
logger.debug(`Reading message #${counter} - ${message.attributes.uid}`)
let to = message.parts.filter(part => {
return part.which === 'HEADER.FIELDS (TO)'
})
to = to[0].body.to[0].replace(/[\<\>]/g, '')
message.parts.filter(part => {
return part.which === 'TEXT'
}).map(part => {
const linkRE = /(https\:\/\/club[a-z0-9\.\/\-]*)\b/g
let link = linkRE.exec(part.body)
link = link[0]
let _
let login
[login, _] = to.split('@')
searchAccount(mysql_connection, login).then(id => {
if (id == null) {
return insertAccount(mysql_connection, login, to)
} else {
return id
}
})
.then(id => {
return validateAccount(link, id, login, config.get('default_password'))
})
.then(details => {
let activated
let id
[activated, id] = details
return updateAccount(mysql_connection, activated, id)
})
.then(() => {
return imap_connection.addFlags(message.attributes.uid, 'SEEN')
})
.then(() => {
logger.debug(`Email ${message.attributes.uid} marked as read.`)
return resolve()
})
.catch(err => {
logger.error(err)
})
})
})
return messagePromise
})
return Promise.all(messagesPromises)
}
const searchMessages = (imap_connection, start, mysql_connection) => {
return imap_connection.openBox('INBOX').then(() => {
const end = start + config.get('imap.batch')
const fetchOpts = {
bodies: [ 'HEADER.FIELDS (TO)', 'TEXT' ],
markSeen: false,
}
let criteria = [
'UNSEEN',
[ 'SUBJECT', 'Trainer Club Activation' ],
[ 'UID', `${start}:${end}` ],
]
logger.info('Searching for unread emails...')
return imap_connection
.search(criteria, fetchOpts)
.then(messages => iterateOverMessages(imap_connection, messages, mysql_connection))
.then(messages => {
if (messages.length >= 0) {
searchMessages(imap_connection, end, mysql_connection)
}
})
})
}
logger.info('Connecting to IMAP server...')
imap.connect(conn).then(connection => {
logger.debug('Connected!')
connection.on('error', (err) => {
logger.error(err)
})
const mysql_connection = mysql.createConnection(config.get('mysql'))
logger.debug('Connecting to MySQL server...')
mysql_connection.connect((err) => {
if (err) {
logger.error('Failed to connect to MySQL server. Error: ' + err)
process.exit(1)
}
})
mysql_connection.on('error', function(err) {
console.log(err.code);
process.exit(0)
});
logger.debug('Opening the inbox folder...')
searchMessages(connection, config.get('imap.start'), mysql_connection).then(() => {
logger.info(`Done. ${messages.length} messages marked as read.`)
// Clean up
connection.end()
mysql_connection.end()
process.exit(0)
})
}).catch(reason => {
logger.error(reason)
})