Skip to content

Commit

Permalink
implemented authorization middleware before being able to access DB
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanC112 committed Jun 21, 2024
1 parent 546f8ac commit 3b9c56d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
30 changes: 30 additions & 0 deletions middlewares/authorize.ts
Original file line number Diff line number Diff line change
@@ -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;
5 changes: 3 additions & 2 deletions routes/projectsDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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<any> = Object.values(req.body);
const query = `
INSERT INTO projects (name, "short-desc", "long-desc", team, link, image, "tech-stack", cohort, topic)
Expand All @@ -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) {
Expand Down

0 comments on commit 3b9c56d

Please sign in to comment.