Passed
Push — main ( 41db93...062dcb )
by Julia
02:58
created

server/src/middleware/apiKey-handler.js   A

Complexity

Total Complexity 4
Complexity/F 4

Size

Lines of Code 35
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 16
mnd 3
bc 3
fnc 1
dl 0
loc 35
ccs 8
cts 8
cp 1
bpm 3
cpm 4
noi 0
c 0
b 0
f 0
rs 10

1 Function

Rating   Name   Duplication   Size   Complexity  
A apiKey-handler.js ➔ apiKeyHandler 0 24 4
1
// eslint-disable-next-line no-unused-vars
2
import express from "express";
3
import apiKeyModel from "../models/api-key.js";
4
5
/**
6
 *
7
 * @param {express.Request} req
8
 * @param {express.Response} res
9
 * @param {express.NextFunction} next
10
 */
11
async function apiKeyHandler(req, res, next) {
12
13 96
    const apiKey = req.headers['x-api-key'];
14
15 96
    const apiKeyString = Array.isArray(apiKey) ? apiKey[0] : apiKey;
16
17 96
    if (!apiKeyString) {
18 1
        return res.status(401).json({
19
            success: false,
20
            message: 'API key is required.'
21
        });
22
    }
23
24 95
    const isValidKey = await apiKeyModel.checkOne(apiKeyString);
25
26 95
    if (!isValidKey) {
27 1
        return res.status(401).json({
28
            success: false,
29
            message: 'Invalid or missing API key. Access denied.'
30
        });
31
    }
32
33 94
    return next();
34
}
35
36
export default apiKeyHandler;
37