From 7dc1f78c805f5d8c1d84c24b51db840ea5edb05a Mon Sep 17 00:00:00 2001 From: DebaucheryLibrarian Date: Mon, 31 Mar 2025 23:01:29 +0200 Subject: [PATCH] Added optional API key auth to REST API. Returning HTTP status codes from GraphQL API. --- src/stashes.js | 6 +++--- src/web/graphql.js | 4 ++-- src/web/server.js | 13 +++++++++++++ src/web/stashes.js | 2 +- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/stashes.js b/src/stashes.js index 4b44aaa..10966de 100755 --- a/src/stashes.js +++ b/src/stashes.js @@ -271,11 +271,11 @@ export async function removeStash(stashId, sessionUser) { .delete() .returning('*'); - if (removed === 0) { - throw new HttpError('Unable to remove this stash', 400); + if (!removed) { + throw new HttpError('This stash could not be removed', 409); } - return curateStash(stash); + return curateStash(removed); } export async function stashActor(actorId, stashId, sessionUser) { diff --git a/src/web/graphql.js b/src/web/graphql.js index 054ea95..851a929 100644 --- a/src/web/graphql.js +++ b/src/web/graphql.js @@ -138,7 +138,7 @@ export async function graphqlApi(req, res) { }, }); - // console.log(data); + const statusCode = data.errors?.[0]?.originalError.httpCode || 200; - res.send(data); + res.status(statusCode).send(data); } diff --git a/src/web/server.js b/src/web/server.js index 03ded8d..4e1baf3 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -20,6 +20,7 @@ import { fetchMoviesApi } from './movies.js'; import { fetchEntitiesApi } from './entities.js'; import { fetchTagsApi } from './tags.js'; +import { verifyKey } from '../auth.js'; import { graphqlApi } from './graphql.js'; import mainHandler from './main.js'; @@ -120,6 +121,18 @@ export default async function initServer() { res.sendFile(path.join(import.meta.dirname, '../../assets/consent.html')); }); + router.use('/api/*', async (req, res, next) => { + if (req.headers['api-user']) { + await verifyKey(req.headers['api-user'], req.headers['api-key'], req); + + req.user = { // eslint-disable-line no-param-reassign + id: Number(req.headers['api-user']), + }; + } + + next(); + }); + // SESSION router.post('/api/session', loginApi); router.delete('/api/session', logoutApi); diff --git a/src/web/stashes.js b/src/web/stashes.js index a156e22..07299e3 100755 --- a/src/web/stashes.js +++ b/src/web/stashes.js @@ -134,7 +134,7 @@ export async function updateStashGraphql(query, req) { } export async function removeStashApi(req, res) { - await removeStash(Number(req.params.stashId), req.user); + await removeStash(Number(req.params.stashId) || req.params.stashId, req.user); res.status(204).send(); }