server/src/models/api-key.js   A
last analyzed

Complexity

Total Complexity 9
Complexity/F 1.8

Size

Lines of Code 83
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
wmc 9
eloc 26
mnd 4
bc 4
fnc 5
dl 0
loc 83
ccs 17
cts 18
cp 0.9444
rs 10
bpm 0.8
cpm 1.8
noi 0
c 0
b 0
f 0
1
import { db } from "./db.js";
2
import hat from "hat";
3
4
5 1
const apiKey = {
6
    /**
7
     * Associative array with all active API
8
     * keys and their respective type, for
9
     * example: bike, admin, other etc
10
     * @type {Array<String,String>}
11
     */
12
    keys: {},
13
14
    /**
15
     * Gets all active api keys from
16
     * DB and stores in the keys array
17
     */
18
    getActiveFromDB: async function() {
19 5
        this.keys = {};
20 5
        const result = await db.queryNoArgs(`CALL active_api_keys();`);
21
22
        /**
23
         * @type {Array<Object>}
24
         */
25 5
        const activeKeys = result[0];
26
27 5
        for (const elem of activeKeys) {
28 21
            this.keys[elem.key] = elem.client_type_id;
29
        }
30
31
    },
32
33
    /**
34
     * Returns true if the key is valid and active
35
     * @param {String} apiKey 
36
     * @returns {Promise<Boolean>}
37
     */
38
    checkOne: async function(apiKey) {
39 100
        if (Object.keys(this.keys).length === 0) {
40 2
            await this.getActiveFromDB();
41
        }
42
43 100
        return apiKey in this.keys;
44
    },
45
    /**
46
     * Checks if api key belongs to a bike.
47
     * When this method is called the checkOne method
48
     * will always have been called before, thus there
49
     * is no need to check if this.keys is empty
50
     * @param {String} apiKey
51
     */
52
    isBikeKey: function(apiKey) {
53 17
        if (this.keys[apiKey] !== "bike") {
54 2
            throw new Error(`API key '${apiKey}' does not belong to a bike client. Method not allowed`);
55
        }
56
    },
57
    /**
58
     * Registers the email of third party
59
     * to database with a unique api key. The
60
     * key will have the client type "other"
61
     * @param {String} email 
62
     * @returns {Object} associative array with api key and the email
63
     */
64
    newThirdParty: async function(email) {
65 2
        let result = await db.queryNoArgs(`CALL all_keys();`);
66 11
        const allKeys = result[0].map(elem => elem.key);
67
68 2
        let newKey = hat();
69
70 2
        while (allKeys.includes(newKey)) {
71
            newKey = hat();
72
        }
73
74 2
        result = await db.queryWithArgs(`CALL new_third_party(?,?);`, [email, newKey]);
75
76
77 1
        return result[0][0];
78
    }
79
80
81
};
82
83
export default apiKey;
84