Add additional login methods

This commit is contained in:
QuantumEntangledAndy
2024-10-06 14:35:03 +07:00
parent 030313c584
commit 69a604044d
4 changed files with 141 additions and 8 deletions

View File

@ -2,14 +2,18 @@
* When applied, this middleware will ensure the request contains the required header for basic authentication and only
* allow access to the endpoint after successful authentication.
*/
const { getConfig } = require('../util.js');
const { getAllUserHandles, toKey, getPasswordHash } = require('../users.js');
const { getConfig, getConfigValue } = require('../util.js');
const storage = require('node-persist');
const PERUSER_BASIC_AUTH = getConfigValue('perUserBasicAuth', false);
const unauthorizedResponse = (res) => {
res.set('WWW-Authenticate', 'Basic realm="SillyTavern", charset="UTF-8"');
return res.status(401).send('Authentication required');
};
const basicAuthMiddleware = function (request, response, callback) {
const basicAuthMiddleware = async function (request, response, callback) {
const config = getConfig();
const authHeader = request.headers.authorization;
@ -27,11 +31,25 @@ const basicAuthMiddleware = function (request, response, callback) {
.toString('utf8')
.split(':');
if (username === config.basicAuthUser.username && password === config.basicAuthUser.password) {
if (! PERUSER_BASIC_AUTH && username === config.basicAuthUser.username && password === config.basicAuthUser.password) {
return callback();
} else {
return unauthorizedResponse(response);
} else if (PERUSER_BASIC_AUTH) {
const userHandles = await getAllUserHandles();
for (const userHandle of userHandles) {
if (username == userHandle) {
const user = await storage.getItem(toKey(userHandle));
if (user && (user.password && user.password === getPasswordHash(password, user.salt))) {
return callback();
}
else if (user && !user.password && !password) {
// Login to an account without password
return callback();
}
}
}
}
return unauthorizedResponse(response);
};
module.exports = basicAuthMiddleware;