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

Projects Endpoints Fix #49

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
171 changes: 104 additions & 67 deletions backend/package-lock.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"create-db": "node src/create_db.mjs",
"test": "node src/index.js",
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
"db-test": "docker run --rm -P -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD='1234' --name pg postgres:alpine"
"db-test": "docker run --rm -P -p 127.0.0.1:5432:5432 -e POSTGRES_PASSWORD='1234' --name pg postgres:alpine",
"prepare": "husky install"
},
"author": "",
"license": "ISC",
Expand All @@ -21,7 +22,7 @@
},
"devDependencies": {
"@eslint/js": "^9.2.0",
"eslint": "^9.2.0",
"eslint": "^9.3.0",
"globals": "^15.1.0"
}
}
}
15 changes: 7 additions & 8 deletions backend/src/create_db.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import postgres from "postgres"

let sql = postgres('postgresql://postgres:1234@localhost:5432') // will use psql environment variables
const postgres = require("postgres");
let sql = postgres("postgresql://postgres:1234@localhost:5432"); // will use psql environment variables

//await sql`drop database test;`

await sql`create database test;`
await sql`create database test;`;

sql = postgres('postgresql://postgres:1234@localhost:5432/test')
sql = postgres("postgresql://postgres:1234@localhost:5432/test");

await sql`CREATE TABLE newsletter (
newsletter_id SERIAL PRIMARY KEY,
Expand All @@ -17,13 +16,13 @@ await sql`CREATE TABLE newsletter (
length INT,
reading_time INT,
created_time TIMESTAMP WITH TIME ZONE DEFAULT CAST(TIMEOFDAY() AS TIMESTAMP WITH TIME ZONE)
);`
);`;

await sql`INSERT INTO newsletter (newsletter_title, newsletter_body, tags, author, length, reading_time) VALUES ('Tech Trends', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ultricies felis in purus tempus, vitae vestibulum ex tincidunt. Duis rhoncus arcu et urna tempor, at fringilla justo pretium. Integer convallis, eros vitae ultrices pulvinar, urna dui varius dui, id sagittis felis ligula sed justo. Nam tempus turpis et quam sodales vestibulum.', 'technology, trends, coding', 'John Doe', 300, 1);`
await sql`INSERT INTO newsletter (newsletter_title, newsletter_body, tags, author, length, reading_time) VALUES ('Tech Trends', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ultricies felis in purus tempus, vitae vestibulum ex tincidunt. Duis rhoncus arcu et urna tempor, at fringilla justo pretium. Integer convallis, eros vitae ultrices pulvinar, urna dui varius dui, id sagittis felis ligula sed justo. Nam tempus turpis et quam sodales vestibulum.', 'technology, trends, coding', 'John Doe', 300, 1);`;

await sql`CREATE TABLE subscriber (
subscriber_id SERIAL PRIMARY KEY,
email TEXT,
created_time TIMESTAMP WITH TIME ZONE DEFAULT CAST(TIMEOFDAY() AS TIMESTAMP WITH TIME ZONE),
is_verified BOOLEAN DEFAULT false
)`
)`;
35 changes: 21 additions & 14 deletions backend/src/db.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
// // db.js
// const postgres = require("postgres");
// require("dotenv").config({path : 'DatabaseCreds.env'});

// db.js
import postgres from 'postgres'
// /*
// SETTING UP DB CONNECTION
// */

require('dotenv').config()
// const USERNAME = process.env.Db_Username;
// const PASSWORD = process.env.Db_Password;
// const HOST_NAME = process.env.Db_Host;
// const PORT = process.env.Db_Host;
// const DB_NAME = process.env.Db_Database;

/*
SETTING UP DB CONNECTION
*/
// const sql = postgres(
// `postgres://${USERNAME}:${PASSWORD}@${HOST_NAME}:${PORT}/${DB_NAME}`
// );

const USERNAME = process.env.USERNAME
const PASSWORD = process.env.PASSWORD
const HOST_NAME = process.env.HOST_NAME
const PORT = process.env.PORT
const DB_NAME = process.env.DB_NAME
// console.log("USERNAME:", USERNAME);
// console.log("PASSWORD:", PASSWORD);
// console.log("HOST_NAME:", HOST_NAME);
// console.log("PORT:", PORT);
// console.log("DB_NAME:", DB_NAME);
// console.log(sql);

const sql = postgres(`postgres://${USERNAME}:${PASSWORD}@${HOST_NAME}:${PORT}/${DB_NAME}`)

export default sql
// module.exports = sql;
73 changes: 40 additions & 33 deletions backend/src/dbScript.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
import sql from './db.js'
const sql = require("./db.js");

/**
* @createDB function to create db
/* @createDB function to create db
* @createEventsTable function to create Events table
* @getEvents function to retreive all events
* @createEvent function to insert an event record
* @params : id,ename,ebody,edesc,etags,time_conducted,room_number,status
*
*
* @getEventByName function to get event by its name
* @params : name of the event
*/

async function createDB(name) {
const users = await sql`
CREATE DATABASE ${ name }
`
await sql`
CREATE DATABASE ${name}
`;
}

async function createEventsTable() {
//CREATE ENUM TYPE FOR STATUS
await sql`
//CREATE ENUM TYPE FOR STATUS
await sql`
CREATE TYPE status_state AS ENUM ('ended','upcoming');

`
// CREATE EVENTS TABLE
await sql`
`;
// CREATE EVENTS TABLE
await sql`
CREATE TABLE Events(
eid INT PRIMARY KEY,
ename VARCHAR(255),
Expand All @@ -38,33 +37,41 @@ async function createEventsTable() {
default current_timestamp,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
`
}
`;
}

async function getEvents(){
const events = await sql`
async function getEvents() {
const events = await sql`
select * from events
`
}
`;
return events;
}

async function getEventById(id){
const events = await sql`
async function getEventById(id) {
const events = await sql`
select * from events where eid = ${id}
`
}
`;
return events;
}

async function createEvent(event){
// INSERT ROW INTO EVENTS
async function createEvent(event) {
// INSERT ROW INTO EVENTS

// Destructuring the events object
const {id,ename,ebody,edesc,etags,time_conducted,room_number,status} = event;
// Destructuring the events object
const {
id,
ename,
ebody,
edesc,
etags,
time_conducted,
room_number,
status,
} = event;

await sql `
await sql`
insert into Events values(${id},${ename},${ebody},${edesc},${etags},${time_conducted},${room_number},${status})
`
}

module.exports = {getEvents,getEventById,createEvent}


`;
}

module.exports = {createDB , createEventsTable, getEvents, getEventById, createEvent };
10 changes: 4 additions & 6 deletions backend/src/events/endpoints/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,26 @@ var jsonParser = bodyParser.json()

router.get('/', auth, async (req, res) => {
let result = await getEvents();
res.send('message':'events fetched', 'data': result });
res.send({'message' : 'events fetched', 'data': result});
})

router.get('/:eventId', auth, async (req, res) => {
let id = req.params.eventId;
const result = await getEventById();
const result = await getEventById(id);
res.send({ 'message': 'event fetched', 'data': result })
})

router.post('/', jsonParser, auth, async (req, res) => {
let event = req.body;

let result = await createEvent(event);

res.send({ 'message': 'event inserted', 'data': result })
})

router.put('/:eventId', auth, jsonParser, async (req, res) => {
let id = req.params.eventId;
let event = req.body;
//let event = req.body;

let result = await sql`update newsletter set ${sql(newsletter, 'newsletter_title', 'newsletter_body', 'tags', 'author', 'length', 'reading_time')
let result = await sql`update newsletter set ${sql('newsletter', 'newsletter_title', 'newsletter_body', 'tags', 'author', 'length', 'reading_time')
}
where newsletter_id = ${id} returning *`

Expand Down
17 changes: 11 additions & 6 deletions backend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ require('dotenv').config()

const express = require('express')

const newsletter = require('./newsletter/endpoints/data.js')
const subscription = require('./newsletter/endpoints/subscription.js')
// const newsletter = require("./newsletter/endpoints/data.js");
// const subscription = require("./newsletter/endpoints/subscription.js");

const app = express()
const port = 3000
//verifying endpoints for projects
const projects = require("./projects/endpoints/data.js");

app.use('/newsletters', newsletter)
app.use('/subscriptions', subscription)
const app = express();
const port = 3000;

app.use("/projects", projects);

// app.use("/newsletters", newsletter);
// app.use("/subscriptions", subscription);

app.get('/', (req, res) => {
res.send('Hello World!');
Expand Down
1 change: 1 addition & 0 deletions backend/src/middleware/api_keys.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API_KEY = abcdefg12345679
29 changes: 21 additions & 8 deletions backend/src/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
var sha256 = require('js-sha256');
const sha256 = require("js-sha256");
const dotenv = require("dotenv");
const path = require('path')

// Load environment variables from the new .env file
dotenv.config({ path: path.join(__dirname, "api_keys.env") });

module.exports = function (req, res, next) {
if (sha256(process.env.api_key) === req.headers.authorization) {
next()
} else {
let error = new Error("Unauthorized.")
next(error)
}
}
const apiKey = process.env.API_KEY;

console.log("API Key from Environment:", apiKey);
console.log("Authorization Header:", req.headers.authorization);
if (!apiKey) {
return next(new Error("NO Api Key set"));
}

if (sha256(apiKey) === req.headers.authorization) {
next();
} else {
let error = new Error("Unauthorized.");
next(error);
}
};
Loading