From 443ef23670f90478eecb033986df3f3e490c8993 Mon Sep 17 00:00:00 2001 From: LordFarquaadtheCreator Date: Mon, 5 Aug 2024 15:37:02 -0400 Subject: [PATCH] migrating to auth bearer username and password --- middlewares/authorize.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/middlewares/authorize.ts b/middlewares/authorize.ts index c83943e..6e293cb 100644 --- a/middlewares/authorize.ts +++ b/middlewares/authorize.ts @@ -1,17 +1,30 @@ import { queryDatabase } from "routes/databaseFunctions"; const authorize = function () { + // auth bearer token + const getBasicAuthCredentials = (req: any) => { + const authHeader = req.headers.authorization; + if (!authHeader || !authHeader.startsWith('Basic ')) { + throw new Error('Missing or invalid Authorization header'); + } + + const base64Credentials = authHeader.split(' ')[1]; + const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii'); + const [username, password] = credentials.split(':'); + + return { username, password }; + }; + return async (req: any, res: any, next: any) => { try { - const name = req.headers.name.toLowerCase(); - const key = req.headers.authorization?.split(" ")[1]; + const { username: name, password: key } = getBasicAuthCredentials(req); const query = { text: "SELECT * FROM apikey WHERE name = $1 AND apikey = $2", values: [name, key] } if (!name || !key) { - return res.status(400).json({ message: "Please enter your name and key before accessing the database!" }); + return res.status(400).json({ message: "Please enter your name and key in auth!" }); } const result = await queryDatabase(req.client, query.text, query.values);