Passed
Push — main ( 74e679...90c63f )
by Julia
01:01 queued 20s
created

apiKey-handler.js ➔ apiKeyHandler   A

Complexity

Conditions 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 24
c 0
b 0
f 0
rs 9.75
cc 4
1
import express from "express";
2
import apiKeyModel from "../models/api-key.js";
3
4
/**
5
 *
6
 * @param {express.Request} req
7
 * @param {express.Response} res
8
 * @param {express.NextFunction} next
9
 */
10
async function apiKeyHandler(req, res, next) {
11
12
    const apiKey = req.headers['x-api-key'];
13
14
    const apiKeyString = Array.isArray(apiKey) ? apiKey[0] : apiKey;
15
16
    if (!apiKeyString) {
17
        return res.status(401).json({
18
            success: false,
19
            message: 'API key is required.'
20
        });
21
    }
22
23
    const isValidKey = await apiKeyModel.checkOne(apiKeyString);
24
25
    if (!isValidKey) {
26
        return res.status(401).json({
27
            success: false,
28
            message: 'Invalid or missing API key. Access denied.'
29
        });
30
    }
31
32
    next();
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
33
}
34
35
export default apiKeyHandler;
36