This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 121
/
index.js
354 lines (316 loc) · 9.9 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
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
347
348
349
350
351
352
353
354
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const path = require('path');
const buf = require('buf').hex;
const hex = require('buf').to.hex;
const mysql = require('mysql');
const MysqlPatcher = require('mysql-patcher');
const encrypt = require('../../encrypt');
const logger = require('../../logging')('db.mysql');
const P = require('../../promise');
const unique = require('../../unique');
const patch = require('./patch');
function MysqlStore(options) {
if (options.charset && options.charset !== 'UTF8_UNICODE_CI') {
logger.warn('createDatabase', { charset: options.charset });
} else {
options.charset = 'UTF8_UNICODE_CI';
}
options.typeCast = function(field, next) {
if (field.type === 'TINY' && field.length === 1) {
return field.string() === '1';
}
return next();
};
logger.info('pool.create', { options: options });
var pool = this._pool = mysql.createPool(options);
pool.on('enqueue', function() {
logger.info('pool.enqueue', {
queueLength: pool._connectionQueue && pool._connectionQueue.length
});
});
}
// Apply patches up to the current patch level.
// This will also create the DB if it is missing.
function updateDbSchema(patcher) {
logger.verbose('updateDbSchema', patcher.options);
var d = P.defer();
patcher.patch(function(err) {
if (err) {
logger.error('updateDbSchema', err);
return d.reject(err);
}
d.resolve();
});
return d.promise;
}
// Sanity-check that we're working with a compatible patch level.
function checkDbPatchLevel(patcher) {
logger.verbose('checkDbPatchLevel', patcher.options);
var d = P.defer();
patcher.readDbPatchLevel(function(err) {
if (err) {
logger.error('checkDbPatchLevel', err);
return d.reject(err);
}
// We are only guaranteed to run correctly if we're at the current
// patch level for this version of the code (the normal state of
// affairs) or the one immediately above it (during a deployment).
if (patcher.currentPatchLevel !== patch.level) {
if (patcher.currentPatchLevel !== patch.level + 1) {
err = 'unexpected db patch level: ' + patcher.currentPatchLevel;
logger.error('checkDbPatchLevel', err);
return d.reject(new Error(err));
}
}
d.resolve();
});
return d.promise;
}
MysqlStore.connect = function mysqlConnect(options) {
options.createDatabase = options.createSchema;
options.dir = path.join(__dirname, 'patches');
options.metaTable = 'dbMetadata';
options.patchKey = 'schema-patch-level';
options.patchLevel = patch.level;
options.mysql = mysql;
var patcher = new MysqlPatcher(options);
return P.promisify(patcher.connect, patcher)().then(function() {
if (options.createSchema) {
return updateDbSchema(patcher);
}
}).then(function() {
return checkDbPatchLevel(patcher);
}).then(function() {
return P.promisify(patcher.end, patcher)();
}).then(function() {
return new MysqlStore(options);
});
};
const QUERY_CLIENT_REGISTER =
'INSERT INTO clients ' +
'(id, name, imageUri, secret, redirectUri, whitelisted, canGrant) ' +
'VALUES (?, ?, ?, ?, ?, ?, ?);';
const QUERY_CLIENT_GET = 'SELECT * FROM clients WHERE id=?';
const QUERY_CLIENT_LIST = 'SELECT id, name, redirectUri, imageUri, canGrant, ' +
'whitelisted FROM clients';
const QUERY_CLIENT_UPDATE = 'UPDATE clients SET ' +
'name=COALESCE(?, name), imageUri=COALESCE(?, imageUri), ' +
'secret=COALESCE(?, secret), redirectUri=COALESCE(?, redirectUri), ' +
'whitelisted=COALESCE(?, whitelisted), canGrant=COALESCE(?, canGrant) ' +
'WHERE id=?';
const QUERY_CLIENT_DELETE = 'DELETE FROM clients WHERE id=?';
const QUERY_CODE_INSERT =
'INSERT INTO codes (clientId, userId, email, scope, authAt, code) ' +
'VALUES (?, ?, ?, ?, ?, ?)';
const QUERY_TOKEN_INSERT =
'INSERT INTO tokens (clientId, userId, email, scope, type, token) VALUES ' +
'(?, ?, ?, ?, ?, ?)';
const QUERY_TOKEN_FIND = 'SELECT * FROM tokens WHERE token=?';
const QUERY_CODE_FIND = 'SELECT * FROM codes WHERE code=?';
const QUERY_CODE_DELETE = 'DELETE FROM codes WHERE code=?';
const QUERY_TOKEN_DELETE = 'DELETE FROM tokens WHERE token=?';
const QUERY_TOKEN_DELETE_USER = 'DELETE FROM tokens WHERE userId=?';
const QUERY_CODE_DELETE_USER = 'DELETE FROM codes WHERE userId=?';
function firstRow(rows) {
return rows[0];
}
function releaseConn(connection) {
connection.release();
}
MysqlStore.prototype = {
ping: function ping() {
logger.debug('ping');
// see bluebird.using():
// https://github.com/petkaantonov/bluebird/blob/master/API.md#resource-management
return P.using(this._getConnection(), function(conn) {
return new P(function(resolve, reject) {
conn.ping(function(err) {
if (err) {
logger.error('ping:', err);
reject(err);
} else {
resolve();
}
});
});
});
},
// createdAt is DEFAULT NOW() in the schema.sql
registerClient: function registerClient(client) {
var id;
if (client.id) {
id = buf(client.id);
} else {
id = unique.id();
}
logger.debug('registerClient', { name: client.name, id: hex(id) });
return this._write(QUERY_CLIENT_REGISTER, [
id,
client.name,
client.imageUri,
buf(client.hashedSecret),
client.redirectUri,
!!client.whitelisted,
!!client.canGrant
]).then(function() {
logger.debug('registerClient.success', { id: hex(id) });
client.id = id;
return client;
});
},
updateClient: function updateClient(client) {
if (!client.id) {
return P.reject(new Error('Update client needs an id'));
}
var secret = client.hashedSecret || client.secret || null;
if (secret) {
secret = buf(secret);
}
return this._write(QUERY_CLIENT_UPDATE, [
// VALUES
client.name,
client.imageUri,
secret,
client.redirectUri,
client.whitelisted,
client.canGrant,
// WHERE
buf(client.id)
]);
},
getClient: function getClient(id) {
return this._readOne(QUERY_CLIENT_GET, [buf(id)]);
},
getClients: function getClients() {
return this._read(QUERY_CLIENT_LIST);
},
removeClient: function removeClient(id) {
return this._write(QUERY_CLIENT_DELETE, [buf(id)]);
},
generateCode: function generateCode(clientId, userId, email, scope, authAt) {
var code = unique.code();
var hash = encrypt.hash(code);
return this._write(QUERY_CODE_INSERT, [
clientId,
userId,
email,
scope.join(' '),
authAt,
hash
]).then(function() {
return code;
});
},
getCode: function getCode(code) {
logger.debug('getCode');
var hash = encrypt.hash(code);
return this._readOne(QUERY_CODE_FIND, [hash]).then(function(code) {
if (code) {
code.scope = code.scope.split(' ');
}
return code;
});
},
removeCode: function removeCode(id) {
return this._write(QUERY_CODE_DELETE, [id]);
},
generateToken: function generateToken(vals) {
var t = {
clientId: vals.clientId,
userId: vals.userId,
email: vals.email,
scope: vals.scope,
type: 'bearer'
};
var _token = unique.token();
var me = this;
var hash = encrypt.hash(_token);
return me._write(QUERY_TOKEN_INSERT, [
t.clientId,
t.userId,
t.email,
t.scope.join(' '),
t.type,
hash
]).then(function() {
t.token = _token;
return t;
});
},
getToken: function getToken(token) {
return this._readOne(QUERY_TOKEN_FIND, [buf(token)]).then(function(t) {
if (t) {
t.scope = t.scope.split(' ');
}
return t;
});
},
removeToken: function removeToken(id) {
return this._write(QUERY_TOKEN_DELETE, [buf(id)]);
},
getEncodingInfo: function getEncodingInfo() {
var info = {};
var me = this;
var qry = 'SHOW VARIABLES LIKE "%character\\_set\\_%"';
return this._read(qry).then(function(rows) {
/*jshint camelcase:false*/
rows.forEach(function(row) {
info[row.Variable_name] = row.Value;
});
qry = 'SHOW VARIABLES LIKE "%collation\\_%"';
return me._read(qry).then(function(rows) {
rows.forEach(function(row) {
info[row.Variable_name] = row.Value;
});
return info;
});
});
},
removeUser: function removeUser(userId) {
// TODO this should be a transaction or stored procedure
var id = buf(userId);
return this._write(QUERY_TOKEN_DELETE_USER, [id])
.then(this._write.bind(this, QUERY_CODE_DELETE_USER, [id]));
},
_write: function _write(sql, params) {
return this._query(this._pool, sql, params);
},
_read: function _read(sql, params) {
return this._query(this._pool, sql, params);
},
_readOne: function _readOne(sql, params) {
return this._read(sql, params).then(firstRow);
},
_getConnection: function _getConnection() {
// see bluebird.using()/disposer():
// https://github.com/petkaantonov/bluebird/blob/master/API.md#resource-management
//
// tl;dr: using() and disposer() ensures that the dispose method will
// ALWAYS be called at the end of the promise stack, regardless of
// various errors thrown. So this should ALWAYS release the connection.
var pool = this._pool;
return new P(function(resolve, reject) {
pool.getConnection(function(err, conn) {
if (err) {
reject(err);
} else {
resolve(conn);
}
});
}).disposer(releaseConn);
},
_query: function _query(connection, sql, params) {
return new P(function(resolve, reject) {
connection.query(sql, params || [], function(err, results) {
if (err) {
reject(err);
} else {
resolve(results);
}
});
});
}
};
module.exports = MysqlStore;