1
|
|
|
import { db } from "./db.js"; |
2
|
|
|
import hat from "hat"; |
3
|
|
|
|
4
|
|
|
|
5
|
1 |
|
const apiKey = { |
6
|
|
|
/** |
7
|
|
|
* An array with all active API keys |
8
|
|
|
* @type {Array<String,String>} |
9
|
|
|
*/ |
10
|
|
|
keys: {}, |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Gets all active api keys from |
14
|
|
|
* DB and stores in the keys array |
15
|
|
|
*/ |
16
|
|
|
getActiveFromDB: async function() { |
17
|
5 |
|
this.keys = {} |
18
|
5 |
|
const result = await db.queryNoArgs(`CALL active_api_keys();`); |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @type {Array<Object>} |
22
|
|
|
*/ |
23
|
5 |
|
const activeKeys = result[0]; |
24
|
|
|
|
25
|
5 |
|
for (const elem of activeKeys) { |
26
|
21 |
|
this.keys[elem.key] = elem.client_type_id; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
}, |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Returns true if the key is valid and active |
33
|
|
|
* @param {String} apiKey |
34
|
|
|
* @returns {Promise<Boolean>} |
35
|
|
|
*/ |
36
|
|
|
checkOne: async function(apiKey) { |
37
|
98 |
|
if (Object.keys(this.keys).length === 0) { |
38
|
2 |
|
await this.getActiveFromDB(); |
39
|
|
|
} |
40
|
|
|
|
41
|
98 |
|
return apiKey in this.keys; |
42
|
|
|
}, |
43
|
|
|
/** |
44
|
|
|
* Checks if api key belongs to a bike. |
45
|
|
|
* When this method is called the checkOne method |
46
|
|
|
* will always have been called before, thus there |
47
|
|
|
* is no need to check if this.keys is empty |
48
|
|
|
* @param {String} apiKey |
49
|
|
|
*/ |
50
|
|
|
isBikeKey: function(apiKey) { |
51
|
11 |
|
if (this.keys[apiKey] !== "bike") { |
52
|
2 |
|
throw new Error(`API key '${apiKey}' does not belong to a bike client. Method not allowed`) |
53
|
|
|
} |
54
|
|
|
}, |
55
|
|
|
|
56
|
|
|
newThirdParty: async function(email) { |
57
|
2 |
|
let result = await db.queryNoArgs(`CALL all_keys();`); |
58
|
11 |
|
const allKeys = result[0].map(elem => elem.key); |
59
|
|
|
|
60
|
2 |
|
let newKey = hat(); |
61
|
|
|
|
62
|
2 |
|
while (allKeys.includes(newKey)) { |
63
|
|
|
newKey = hat(); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
result = await db.queryWithArgs(`CALL new_third_party(?,?);`, [email, newKey]); |
67
|
|
|
|
68
|
|
|
|
69
|
1 |
|
return result[0][0]; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
|
73
|
|
|
}; |
74
|
|
|
|
75
|
|
|
export default apiKey; |
76
|
|
|
|