Skip to content

Commit

Permalink
Merge pull request #13 from blockchainuci/task-3-branch-from-task-2
Browse files Browse the repository at this point in the history
Task 3 branch from task 2
  • Loading branch information
NwinNwin authored Feb 11, 2025
2 parents fdb7da9 + ddd8406 commit 5fc4437
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 19 deletions.
28 changes: 28 additions & 0 deletions backend/middleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const admin = require("../config/firebase-config");

class Middleware {
async decodeToken(req, res, next) {
let token;
if (req.headers.authorization) {
token = req.headers.authorization.split(" ")[1];
}

if (!token || token == "Bearer") {
return res.status(401).json({ message: "Firebase ID token not provided" });
}

try {
const decodeValue = await admin.auth().verifyIdToken(token);
if (decodeValue) {
req.user = decodeValue; // Attach user info to request
return next();
}
return res.status(403).json({ message: "Unauthorized access" });
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Internal server error" });
}
}
}

module.exports = new Middleware();
7 changes: 4 additions & 3 deletions backend/routes/carbon.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
const express = require("express");
const router = express.Router();
const pool = require("../db");
const middleware = require("../middleware");

// Create carbon data
router.post("/", async (req, res) => {
router.post("/", middleware.decodeToken, async (req, res) => {
try {
const {
item_id,
Expand Down Expand Up @@ -117,7 +118,7 @@ router.get("/:id", async (req, res) => {
});

// Update carbon data
router.put("/:id", async (req, res) => {
router.put("/:id", middleware.decodeToken, async (req, res) => {
try {
const { id } = req.params;
const {
Expand Down Expand Up @@ -171,7 +172,7 @@ router.put("/:id", async (req, res) => {
});

// Delete carbon data
router.delete("/:id", async (req, res) => {
router.delete("/:id", middleware.decodeToken, async (req, res) => {
try {
const { id } = req.params;
const deleteCarbon = await pool.query(
Expand Down
10 changes: 6 additions & 4 deletions backend/routes/items.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ const express = require("express");
const router = express.Router();
const pool = require("../db");
const OpenAI = require("openai");
const middleware = require("../middleware");

// Initialize OpenAI configuration
const openai = new OpenAI({
apiKey: process.env.OPEN_AI_API_KEY,
});

// Create item with GPT-generated details using vision
router.post("/", async (req, res) => {
router.post("/", middleware.decodeToken, async (req, res) => {
try {
const {
name,
Expand Down Expand Up @@ -182,7 +183,8 @@ router.get("/:id", async (req, res) => {
});

// Update item
router.put("/:id", async (req, res) => {

router.put("/:id", middleware.decodeToken, async (req, res) => {
try {
const { id } = req.params;
const {
Expand Down Expand Up @@ -217,7 +219,7 @@ router.put("/:id", async (req, res) => {
});

// Delete item
router.delete("/:id", async (req, res) => {
router.delete("/:id", middleware.decodeToken, async (req, res) => {
try {
const { id } = req.params;
await pool.query("DELETE FROM items WHERE id = $1", [id]);
Expand All @@ -229,7 +231,7 @@ router.delete("/:id", async (req, res) => {
});

// Emission Calculator
router.post("/emission-calculator", async (req, res) => {
router.post("/emission-calculator", middleware.decodeToken, async (req, res) => {
try {
const {
estimated_weight_kg,
Expand Down
7 changes: 4 additions & 3 deletions backend/routes/lenders.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const router = require("express").Router();
const pool = require("../db");
const middleware = require("../middleware");

// Create lender record
router.post("/", async (req, res) => {
router.post("/", middleware.decodeToken, async (req, res) => {
try {
const { item_id, email } = req.body;
const newLender = await pool.query(
Expand Down Expand Up @@ -63,7 +64,7 @@ router.get("/:item_id", async (req, res) => {
});

// Update lender status
router.put("/:item_id", async (req, res) => {
router.put("/:item_id", middleware.decodeToken, async (req, res) => {
try {
const { item_id } = req.params;
const { is_picked_up, is_returned } = req.body;
Expand Down Expand Up @@ -125,7 +126,7 @@ router.put("/:item_id", async (req, res) => {
});

// Delete lender record
router.delete("/:item_id", async (req, res) => {
router.delete("/:item_id", middleware.decodeToken, async (req, res) => {
try {
const { item_id } = req.params;
await pool.query("DELETE FROM lender WHERE item_id = $1", [item_id]);
Expand Down
7 changes: 4 additions & 3 deletions backend/routes/renters.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const router = require("express").Router();
const pool = require("../db");
const middleware = require("../middleware");

// Create renter record
router.post("/", async (req, res) => {
router.post("/", middleware.decodeToken, async (req, res) => {
try {
const { item_id, email } = req.body;
const newRenter = await pool.query(
Expand Down Expand Up @@ -63,7 +64,7 @@ router.get("/:item_id", async (req, res) => {
});

// Update renter status
router.put("/:item_id", async (req, res) => {
router.put("/:item_id", middleware.decodeToken, async (req, res) => {
try {
const { item_id } = req.params;
const { is_picked_up, is_returned } = req.body;
Expand Down Expand Up @@ -125,7 +126,7 @@ router.put("/:item_id", async (req, res) => {
});

// Delete renter record
router.delete("/:item_id", async (req, res) => {
router.delete("/:item_id", middleware.decodeToken, async (req, res) => {
try {
const { item_id } = req.params;
await pool.query("DELETE FROM renter WHERE item_id = $1", [item_id]);
Expand Down
7 changes: 4 additions & 3 deletions backend/routes/users.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const router = require("express").Router();
const pool = require("../db");
const middleware = require("../middleware");

// Create user
router.post("/", async (req, res) => {
router.post("/", middleware.decodeToken, async (req, res) => {
try {
const { email, wallet_address } = req.body;
const newUser = await pool.query(
Expand Down Expand Up @@ -40,7 +41,7 @@ router.get("/:id", async (req, res) => {
});

// Update user
router.put("/:id", async (req, res) => {
router.put("/:id", middleware.decodeToken, async (req, res) => {
try {
const { id } = req.params;
const { email, wallet_address } = req.body;
Expand All @@ -56,7 +57,7 @@ router.put("/:id", async (req, res) => {
});

// Delete user
router.delete("/:id", async (req, res) => {
router.delete("/:id", middleware.decodeToken, async (req, res) => {
try {
const { id } = req.params;
await pool.query("DELETE FROM users WHERE id = $1", [id]);
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/contexts/AuthContext.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createContext, useContext, useState, useEffect } from "react";
import { auth } from "../firebase";
import { getAuth } from "firebase/auth";

const AuthContext = createContext();

Expand Down Expand Up @@ -31,3 +32,12 @@ export function AuthProvider({ children }) {
</AuthContext.Provider>
);
}

export async function getBearerToken() {
const auth = getAuth();
const user = auth.currentUser;
if (user) {
return await user.getIdToken();
}
return null;
}
2 changes: 1 addition & 1 deletion frontend/src/pages/ChatPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from "@chakra-ui/react";
import { useState, useEffect, useRef } from "react";
import axios from "axios";
import { io } from "socket.io-client";
//import { io } from "socket.io-client";


/* Sample Data */
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/pages/CheckoutPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import { useState, useEffect } from "react";
import { auth } from "../firebase";
import axios from "axios";
import { getBearerToken } from "../contexts/AuthContext";

function CheckoutPage() {
const { id } = useParams();
Expand Down Expand Up @@ -75,17 +76,28 @@ function CheckoutPage() {

const handleSubmitPayment = async () => {
try {
const token = await getBearerToken();
// First update the item with days_rented
await axios.put(`http://localhost:3001/items/${id}`, {
...item, // Spread existing item properties
days_rented: days, // Add the new days_rented value
status: "Awaiting Pickup",
},
{
headers: {
Authorization: `Bearer ${token}`,
},
});

// Then create renter record
await axios.post("http://localhost:3001/renters", {
item_id: parseInt(id),
email: userEmail,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
});

// Navigate to confirmation page
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/pages/LendPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
FaTree,
FaEye,
} from "react-icons/fa";
import { getBearerToken } from "../contexts/AuthContext";

function LendPage() {
const [items, setItems] = useState([]);
Expand Down Expand Up @@ -83,10 +84,16 @@ function LendPage() {
}, [userEmail]);

const handlePickupConfirmation = async (itemId) => {
const token = await getBearerToken();
try {
await axios.put(`http://localhost:3001/lenders/${itemId}`, {
is_picked_up: true,
is_returned: false,
},
{
headers: {
Authorization: `Bearer ${token}`
}
});

// Navigate to waiting page
Expand All @@ -99,9 +106,15 @@ function LendPage() {

const handleReturnConfirmation = async (itemId) => {
try {
const token = await getBearerToken();
await axios.put(`http://localhost:3001/lenders/${itemId}`, {
is_picked_up: true,
is_returned: true,
},
{
headers: {
Authorization: `Bearer ${token}`
}
});

// Navigate to waiting page
Expand Down
9 changes: 7 additions & 2 deletions frontend/src/pages/ListItemPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage";
import { storage, auth } from "../firebase";
import axios from "axios";
import { useNavigate } from "react-router-dom";

import { getBearerToken } from "../contexts/AuthContext";
function ListItemPage() {
const [images, setImages] = useState([]);
const [imageFiles, setImageFiles] = useState(Array(4).fill(null));
Expand Down Expand Up @@ -91,7 +91,7 @@ function ListItemPage() {
alert("Please fill in all required fields");
return;
}

const token = await getBearerToken();
// Create item in database with email
const response = await axios.post(`http://localhost:3001/items`, {
name,
Expand All @@ -102,6 +102,11 @@ function ListItemPage() {
images,
email: userEmail,
status: "Listed",
},
{
headers: {
Authorization: `Bearer ${token}`
}
});

alert("Item listed successfully");
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/pages/RentPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
FaTree,
FaEye,
} from "react-icons/fa";
import { getBearerToken } from "../contexts/AuthContext";

function RentPage() {
const [items, setItems] = useState([]);
Expand Down Expand Up @@ -80,10 +81,16 @@ function RentPage() {
}, [userEmail]);

const handlePickupConfirmation = async (itemId) => {
const token = await getBearerToken();
try {
await axios.put(`http://localhost:3001/renters/${itemId}`, {
is_picked_up: true,
is_returned: false,
},
{
headers: {
Authorization: `Bearer ${token}`
}
});

// Navigate to waiting page
Expand All @@ -95,10 +102,16 @@ function RentPage() {
};

const handleReturnConfirmation = async (itemId) => {
const token = await getBearerToken();
try {
await axios.put(`http://localhost:3001/renters/${itemId}`, {
is_picked_up: true,
is_returned: true,
},
{
headers: {
Authorization: `Bearer ${token}`
}
});

// Navigate to waiting page
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/pages/SignUpPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { auth } from "../firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import { getBearerToken } from "../contexts/AuthContext";
import { FcGoogle } from "react-icons/fc";
import { signInWithPopup } from "firebase/auth";
import { provider } from "../firebase";
Expand All @@ -29,12 +30,19 @@ function SignUpPage() {

try {
// First, create the Firebase auth user
await createUserWithEmailAndPassword(auth, email, password);
const token = await getBearerToken();
const result = await signInWithPopup(auth, provider);

// Then, add user to your database using axios
await axios.post("http://localhost:3001/users", {
email: email,
wallet_address: "0x742d35Cc6634C0532925a3b844Bc454e4438f44e", // Hard-coded wallet address
},
{
headers: {
Authorization: `Bearer ${token}`
}
});

navigate("/");
Expand Down

0 comments on commit 5fc4437

Please sign in to comment.