-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatastore.js
315 lines (251 loc) · 7.64 KB
/
datastore.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
const mysql = require('mysql2/promise')
const config = require('./config')
const crypto = require('crypto')
console.log('Connect DB')
const db = mysql.createPool(config.db.uri)
class DatastoreQuery {
m_dataset = ''
m_filter = []
constructor (dataset) {
// DEBUG
// console.log('new dataset', dataset)
this.m_dataset = dataset
}
filter (key, operator, value) {
this.m_filter.push({key, operator, value})
return this
}
async update (data) {
// console.log(this.m_dataset, this.m_filter, data)
const conn = await db.getConnection()
const updateValues = Object.keys(data).map(f => {
return '`' + f + '` = ?'
}).join(', ')
const whereQuery = this.m_filter.map(f => {
return '`' + f.key + '` ' + f.operator + ' ?'
}).join(' AND ')
const query = `
UPDATE ${this.m_dataset}s
SET ${updateValues}
WHERE ${whereQuery}
`
const params = [
...Object.keys(data).map(k => data[k]),
...this.m_filter.map(f => f.value)
]
// console.log(query, params)
const results = await conn.execute(query, params)
conn.release()
return results
}
async get () {
if (this.m_dataset === 'user') {
const conn = await db.getConnection()
const results = await conn.execute(`
SELECT id,
username,
password,
xrpl_account
FROM users
WHERE username = ?
LIMIT 1
`, this.m_filter.filter(f => f.key === 'username').map(f => f.value))
conn.release()
if (Array.isArray(results) && results.length > 0) {
if (Array.isArray(results[0]) && results[0].length > 0) {
const result = (await Promise.all(results[0].map(async r => {
const outcome = await new Promise((resolve, reject) => {
if ((Number(r?.xrpl_account || 0) || 0) > 0) {
// XRPL account, no need for password check if XUMM flow.
const account = this.m_filter.filter(f => f.key === 'username').map(f => f.value)[0]
const pwhash = crypto.createHash('sha256').update(account + config.secret).digest('hex')
if (this.m_filter.filter(f => f.key === 'password').map(f => f.value)[0] === pwhash) {
// console.log('xrpl account outcome r', r, this.m_filter.filter(f => f.key === 'password').map(f => f.value)[0])
return resolve({...r, safe: true})
}
}
crypto.pbkdf2(this.m_filter.filter(f => f.key === 'password').map(f => f.value)[0], String(r.id), 100000, 64, 'sha512', (err, derivedKey) => {
if (err) {
console.log(err)
return reject(err)
}
const hashhalf = derivedKey.toString('hex').slice(0, 64)
// console.log({hashhalf})
resolve({...r, safe: hashhalf === r.password})
})
})
return outcome
}))).filter(r => r.safe)
// DEBUG
// console.log('users.match', result)
return result
}
}
} else {
const conn = await db.getConnection()
// DEBUG
// console.log('Use MySQL database @ ', this.m_dataset, this.m_filter)
const whereQuery = this.m_filter.map(f => {
return '`' + f.key + '` ' + f.operator + ' ?'
}).join(' AND ')
const query = `
SELECT *
FROM ${this.m_dataset}s
WHERE ${whereQuery}
`
const results = await conn.execute(query, this.m_filter.map(f => f.value))
conn.release()
if (Array.isArray(results) && results.length > 0) {
if (Array.isArray(results[0]) && results[0].length > 0) {
return results[0]
}
}
}
return []
}
}
class Datastore {
m_databaseConnection = undefined
constructor () {
console.log('Datastore constructed')
}
createQuery (dataset) {
return new DatastoreQuery(dataset)
}
async updateQuery (datstoreQuery, newData) {
try {
const queryResults = await datstoreQuery.update(newData)
// DEBUG
// console.log('updateQuery', newData, queryResults)
return true
} catch (e) {
console.log('error', e.message)
return false
}
}
async runQuery (datstoreQuery) {
try {
const queryResults = await datstoreQuery.get()
// console.log('runQuery', queryResults)
return [ queryResults ]
} catch (e) {
console.log('error', e.message)
return [[]]
}
}
key ([k, v]) {
return {
[k]: v
}
}
async upsert (data) {
console.log('upsert', data)
const upsertData = {}
Object.keys(data).forEach(k => {
Object.keys(data[k]).forEach(fld => {
// console.log(fld, data[k][fld])
upsertData[fld] = data[k][fld]
})
})
const conn = await db.getConnection()
let table = ''
if (upsertData?.authorization_code) {
table = 'grants'
} else
if (upsertData?.xrpl_account) {
table = 'users'
} else
if (upsertData?.payload) {
table = 'xumm_challenges'
} else {
throw new Error('Error, unknown dataset to upsert to')
}
console.log('Use MySQL database @ ', table)
await conn.execute('INSERT IGNORE INTO `' + table + '`' + `
(${Object.keys(upsertData).join(', ')})
VALUES (${Object.keys(upsertData).map(v => '?').join(', ')})
ON DUPLICATE KEY UPDATE
${Object.keys(upsertData).map(v => '`' + v + '` = ?').join(', ')}
`, [
...Object.keys(upsertData).map(k => upsertData[k] || null),
...Object.keys(upsertData).map(k => upsertData[k] || null),
])
conn.release()
}
transaction () {
console.log('Start transaction')
return new DatastoreTransaction()
}
}
class DatastoreTransaction {
_mf_resolveConnection = null
_mf_resolveTransaction = null
m_connection = null
m_transaction = null
constructor () {
this.m_connection = new Promise(resolve => {
this._mf_resolveConnection = resolve
})
this.m_transaction = new Promise(resolve => {
this._mf_resolveTransaction = resolve
})
db.getConnection().then(c => {
this._mf_resolveConnection(c)
console.log('Got connection')
c.beginTransaction().then(t => {
this._mf_resolveTransaction(t)
console.log('Got transaction')
})
})
return this
}
async run () {
console.log('Transaction RUN')
return this
}
async get (key) {
const c = await this.m_connection
if (key?.authorization_code) {
console.log('Transaction GET', key?.authorization_code)
const data = await c.execute(`
SELECT * FROM grants
WHERE authorization_code = ?
AND fetched = 0
ORDER BY exp DESC LIMIT 1
`, [key?.authorization_code])
if (Array.isArray(data) && data.length > 0) {
return data[0]
}
}
throw new Error('Invalid dataset: transaction Get (key)')
}
async delete (key) {
const c = await this.m_connection
if (key?.authorization_code) {
console.log('Transaction DELETE', key?.authorization_code)
const data = await c.execute(`
UPDATE grants SET fetched = 1 WHERE authorization_code = ?
`, [key?.authorization_code])
}
return this
}
async rollback () {
const c = await this.m_connection
console.log('Transaction ROLLBACK')
c.rollback()
c.release()
return this
}
async commit () {
const c = await this.m_connection
const t = await this.m_transaction
console.log('Transaction COMMIT')
c.commit()
c.release()
return this
}
}
module.exports = {
datastore: new Datastore(),
db
}