From 3b9c56def39c99aa456be19edf28d474c3b711dd Mon Sep 17 00:00:00 2001 From: Ivan Chen Date: Fri, 21 Jun 2024 13:12:05 -0400 Subject: [PATCH] implemented authorization middleware before being able to access DB --- middlewares/authorize.ts | 30 ++++++++++++++++++++++++++++++ routes/projectsDB.ts | 5 +++-- 2 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 middlewares/authorize.ts diff --git a/middlewares/authorize.ts b/middlewares/authorize.ts new file mode 100644 index 0000000..3459e8a --- /dev/null +++ b/middlewares/authorize.ts @@ -0,0 +1,30 @@ +import { queryDatabase } from "routes/databaseFunctions"; +import { Client } from "pg"; + +const authorize = function (client: Client) { + return async (req: any, res: any, next: any) => { + const name = req.headers.name.toLowerCase(); + const key = req.headers.authorization?.split(" ")[1]; + 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!" }); + } + + try { + const result = await queryDatabase(client, query.text, query.values); + if (result.rows.length === 0) { + return res.status(401).json({ message: "Invalid name or key!" }); + } + next(); + } + catch (e: any) { + return res.status(500).json({ message: e.message }); + } + } +} + +export default authorize; \ No newline at end of file diff --git a/routes/projectsDB.ts b/routes/projectsDB.ts index 42ca432..7c8a7dc 100644 --- a/routes/projectsDB.ts +++ b/routes/projectsDB.ts @@ -6,6 +6,7 @@ import { Client, QueryResult } from "pg"; import validate from "../middlewares/validate"; import getDB from "../db"; import synchronizeLocal from "../utils/synchronize"; +import authorize from "middlewares/authorize"; const router: Router = Router(); @@ -67,7 +68,7 @@ async function startServer() { } }); - router.post("/add", validate, async (req: any, res: any) => { + router.post("/add", authorize(client), validate, async (req: any, res: any) => { const values: Array = Object.values(req.body); const query = ` INSERT INTO projects (name, "short-desc", "long-desc", team, link, image, "tech-stack", cohort, topic) @@ -81,7 +82,7 @@ async function startServer() { } }); - router.put("/update", validate, async (req: any, res: any) => { + router.put("/update", authorize(client), validate, async (req: any, res: any) => { const projectName = req.query.name; if (!projectName) {