From 3a9f7e443b8dcd6fca41704735399c7c21e42383 Mon Sep 17 00:00:00 2001 From: James Stokes Date: Mon, 26 Jun 2023 22:08:19 +0100 Subject: [PATCH] Sessionless HTTP API authentication by using the WG_PASSWORD in the Authorization header --- src/lib/Server.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/lib/Server.js b/src/lib/Server.js index f8f380bd..34112875 100644 --- a/src/lib/Server.js +++ b/src/lib/Server.js @@ -1,6 +1,7 @@ 'use strict'; const path = require('path'); +const crypto = require('crypto'); const express = require('express'); const expressSession = require('express-session'); @@ -75,6 +76,22 @@ module.exports = class Server { return next(); } + if (req.path.startsWith('/api/') && req.headers['authorization']) { + const authorizationHash = crypto.createHash('sha256') + .update(req.headers['authorization']) + .digest('hex'); + const passwordHash = crypto.createHash('sha256') + .update(PASSWORD) + .digest('hex'); + if (crypto.timingSafeEqual(Buffer.from(authorizationHash), Buffer.from(passwordHash))) { + return next(); + } + + return res.status(401).json({ + error: 'Incorrect Password', + }); + } + return res.status(401).json({ error: 'Not Logged In', });