Total Complexity | 4 |
Complexity/F | 4 |
Lines of Code | 35 |
Function Count | 1 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 0 |
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(); |
||
|
|||
33 | } |
||
34 | |||
35 | export default apiKeyHandler; |
||
36 |