From 51a9783b5db185d2aed5d18a68eacfb6c1471e7e Mon Sep 17 00:00:00 2001 From: Oliver-Akins Date: Fri, 23 Jul 2021 11:47:05 -0600 Subject: [PATCH] Add basic authentication to the API --- src/main.ts | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main.ts b/src/main.ts index 2040389..495b17d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -2,8 +2,7 @@ import "module-alias/register"; // Begin personal code -import { DB_DEFAULTS } from "@/constants"; -import { Server } from "@hapi/hapi"; +import basic from "@hapi/basic"; import path from "path"; import glob from "glob"; import toml from "toml"; @@ -42,6 +41,32 @@ async function init() { port: config.server.port, }); + // Setup authentication + server.register(basic); + server.auth.strategy(`simple`, `basic`, { + async validate(request: Request, user: string, pass: string, h: ResponseToolkit) { + + // Are we attempting to authenticate, then use the auth password + if (request.path === `/discord/auth`) { + return { + isValid: config.discord.auth_password === pass, + credentials: { pass }, + }; + }; + + // Ensure the guild has a config + if (!config.guilds[user]) { + return { isValid: false, }; + }; + + return { + isValid: config.guilds[user].password === pass, + credentials: { user } + }; + }, + allowEmptyUsername: true, + }); + server.auth.default(`simple`) // Register all the routes let files = glob.sync(