Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Authorize User #6

Merged
merged 2 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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