Spaces:
Paused
Paused
Download lib/apiKeyMiddleware.js from Adhyasta/gcs-backend-server: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/spaces/Adhyasta/gcs-backend-server/resolve/main/lib/apiKeyMiddleware.js
- Command line
-
hf download hf://spaces/Adhyasta/gcs-backend-server/lib/apiKeyMiddleware.js
-
curl -L -o apiKeyMiddleware.js https://huggingface.co/spaces/Adhyasta/gcs-backend-server/resolve/main/lib/apiKeyMiddleware.js
2.2 kB
| /** | |
| * API Key authentication middleware | |
| * | |
| * The API key is read from the environment variable API_KEY. | |
| * If API_KEY is not set the middleware is a no-op (useful in local dev). | |
| * | |
| * βββ HTTP (Express) βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| * Clients must supply the key in ONE of the following ways: | |
| * β’ Header: x-api-key: <key> | |
| * β’ Header: Authorization: Bearer <key> | |
| * β’ Query: ?api_key=<key> | |
| * | |
| * βββ WebSocket (Socket.IO) ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| * Clients must supply the key in ONE of the following ways: | |
| * β’ io('<url>', { auth: { apiKey: '<key>' } }) | |
| * β’ io('<url>', { extraHeaders: { 'x-api-key': '<key>' } }) | |
| */ | |
| /** | |
| * Express middleware β runs on every HTTP request. | |
| */ | |
| const httpApiKeyMiddleware = (req, res, next) => { | |
| const apiKey = process.env.API_KEY | |
| // Key not configured β allow all (development mode) | |
| if (!apiKey) return next() | |
| // Skip preflight requests | |
| if (req.method === 'OPTIONS') return next() | |
| const headerKey = | |
| req.headers['x-api-key'] || | |
| (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim() | |
| const queryKey = req.query.api_key | |
| if (headerKey === apiKey || queryKey === apiKey) return next() | |
| return res | |
| .status(401) | |
| .json({ error: 'Unauthorized: invalid or missing API key' }) | |
| } | |
| /** | |
| * Socket.IO middleware β runs on every new connection handshake. | |
| */ | |
| const socketApiKeyMiddleware = (socket, next) => { | |
| const apiKey = process.env.API_KEY | |
| // Key not configured β allow all (development mode) | |
| if (!apiKey) return next() | |
| const fromAuth = | |
| socket.handshake.auth && socket.handshake.auth.apiKey | |
| const fromHeader = | |
| socket.handshake.headers && socket.handshake.headers['x-api-key'] | |
| if (fromAuth === apiKey || fromHeader === apiKey) return next() | |
| return next(new Error('Unauthorized: invalid or missing API key')) | |
| } | |
| module.exports = { httpApiKeyMiddleware, socketApiKeyMiddleware } | |