From eafbde69c37bc7ef72385d175b78b7cb3383fbf7 Mon Sep 17 00:00:00 2001 From: Anshpatel2434 Date: Tue, 2 Jul 2024 22:36:41 +0530 Subject: [PATCH] made the profile and edit profile flawless --- backend/package-lock.json | 9 +- .../20240629113525_newschema/migration.sql | 87 ++++++++++++ backend/prisma/schema.prisma | 54 ++++++-- backend/src/index.ts | 10 +- backend/src/routes/book.ts | 103 ++++++++++++++ backend/src/routes/profile.ts | 110 +++++++++++++++ backend/src/routes/rent.ts | 129 ++++++++++++++++++ backend/src/routes/rentAllRouter.ts | 30 ++++ backend/src/routes/user.ts | 86 +++++++++--- backend/wrangler.toml | 2 +- frontend/src/Components/DropDown.tsx | 6 +- frontend/src/Components/GoogleButton.tsx | 3 - frontend/src/Components/LogInInput.tsx | 3 +- frontend/src/Components/Navbar.tsx | 46 +++---- frontend/src/Components/SignUpInput.tsx | 1 - frontend/src/Context/UseContext.tsx | 43 +++++- frontend/src/Pages/EditProfile.tsx | 44 +++--- frontend/src/Pages/UserInfo.tsx | 7 +- 18 files changed, 668 insertions(+), 105 deletions(-) create mode 100644 backend/prisma/migrations/20240629113525_newschema/migration.sql create mode 100644 backend/src/routes/book.ts create mode 100644 backend/src/routes/profile.ts create mode 100644 backend/src/routes/rent.ts create mode 100644 backend/src/routes/rentAllRouter.ts diff --git a/backend/package-lock.json b/backend/package-lock.json index 2ebd6ec..4dedc52 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -6,7 +6,7 @@ "": { "name": "backend", "dependencies": { - "@anshpatel2434/odoo-combat": "^1.0.0", + "@anshpatel2434/odoo-combat": "^1.0.1", "@prisma/extension-accelerate": "^1.1.0", "hono": "^4.4.7", "prisma": "^5.15.1" @@ -17,9 +17,10 @@ } }, "node_modules/@anshpatel2434/odoo-combat": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@anshpatel2434/odoo-combat/-/odoo-combat-1.0.0.tgz", - "integrity": "sha512-2ZMOdVHsM4aLVK3P+SFGeJ+H+67vDL/d3RlQ/LLqEWLbhqQ8nOB8MBm0LYXiKYFxen2vgasXvYT0uiYzZxDRkw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@anshpatel2434/odoo-combat/-/odoo-combat-1.0.1.tgz", + "integrity": "sha512-WK5suijGsCyAGX7R8+ednGvI+toe4shybVRiFggk+fjQiHFwkcB5R8LhROESnempc8HYVYz1WHa0jD8BR4pXPA==", + "license": "ISC", "dependencies": { "zod": "^3.23.8" } diff --git a/backend/prisma/migrations/20240629113525_newschema/migration.sql b/backend/prisma/migrations/20240629113525_newschema/migration.sql new file mode 100644 index 0000000..3a43a4d --- /dev/null +++ b/backend/prisma/migrations/20240629113525_newschema/migration.sql @@ -0,0 +1,87 @@ +/* + Warnings: + + - You are about to drop the `Customer` table. If the table is not empty, all the data it contains will be lost. + - You are about to drop the `Order` table. If the table is not empty, all the data it contains will be lost. + +*/ +-- DropForeignKey +ALTER TABLE "Order" DROP CONSTRAINT "Order_orderId_fkey"; + +-- DropTable +DROP TABLE "Customer"; + +-- DropTable +DROP TABLE "Order"; + +-- CreateTable +CREATE TABLE "User" ( + "id" TEXT NOT NULL, + "name" TEXT, + "email" TEXT NOT NULL, + "password" TEXT NOT NULL, + + CONSTRAINT "User_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Profile" ( + "id" TEXT NOT NULL, + "username" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "house_no" TEXT NOT NULL, + "street" TEXT NOT NULL, + "city_state" TEXT NOT NULL, + "area" TEXT NOT NULL, + "address" TEXT NOT NULL, + "phone_num" TEXT NOT NULL, + + CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Rented" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "title" TEXT NOT NULL, + "type" TEXT NOT NULL, + "description" TEXT NOT NULL, + "quantity" INTEGER NOT NULL, + "availibility" BOOLEAN NOT NULL, + "availableFrom" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "image" TEXT, + "price" INTEGER NOT NULL, + + CONSTRAINT "Rented_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Booked" ( + "id" TEXT NOT NULL, + "rentedId" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "title" TEXT NOT NULL, + "type" TEXT NOT NULL, + "description" TEXT NOT NULL, + "availableTill" TIMESTAMP(3) NOT NULL, + "quantity" INTEGER NOT NULL, + "image" TEXT, + "price" INTEGER NOT NULL, + + CONSTRAINT "Booked_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "User_email_key" ON "User"("email"); + +-- CreateIndex +CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); + +-- AddForeignKey +ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Rented" ADD CONSTRAINT "Rented_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Booked" ADD CONSTRAINT "Booked_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 0d7bf5c..89762f5 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -13,19 +13,53 @@ datasource db { url = env("DATABASE_URL") } -model Customer { - id Int @id @default(autoincrement()) +model User { + id String @id @default(uuid()) name String? email String @unique password String - orders Order[] + profile Profile? + rented Rented[] + booked Booked[] } -model Order{ - id Int @id @default(autoincrement()) - orderId Int - orderContent String - amount Float - orderAt DateTime @default(now()) - customer Customer @relation(fields: [orderId], references: [id]) +model Profile{ + id String @id @default(uuid()) + username String + user User @relation(fields: [userId], references: [id]) + userId String @unique + house_no String + street String + city_state String + area String + address String + phone_num String } + model Rented{ + id String @id @default(uuid()) + user User @relation(fields: [userId], references: [id]) + userId String + title String + type String + description String + quantity Int + availibility Boolean + availableFrom DateTime @default(now()) + image String? + price Int + } + +model Booked{ + id String @id @default(uuid()) + user User @relation(fields: [userId], references: [id]) + rentedId String + userId String + title String + type String + description String + availableTill DateTime + quantity Int + image String? + price Int +} + diff --git a/backend/src/index.ts b/backend/src/index.ts index bb67738..d6de564 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -1,12 +1,18 @@ import { Hono } from "hono"; import { userRouter } from "./routes/user"; -import { orderRouter } from "./routes/order"; import { cors } from "hono/cors"; +import { rentRouter } from "./routes/rent"; +import { bookRouter } from "./routes/book"; +import { rentAllRouter } from "./routes/rentAllRouter"; +import { profileRouter } from "./routes/profile"; const app = new Hono(); app.use("/*", cors()); app.route("/api/v1/user", userRouter); -app.route("/api/v1/order", orderRouter); +app.route("/api/v1/rent", rentRouter); +app.route("/api/v1/book", bookRouter); +app.route("/api/v1/rentAll", rentAllRouter); +app.route("/api/v1/profile", profileRouter); export default app; diff --git a/backend/src/routes/book.ts b/backend/src/routes/book.ts new file mode 100644 index 0000000..067da24 --- /dev/null +++ b/backend/src/routes/book.ts @@ -0,0 +1,103 @@ +import { Hono } from "hono"; +import { PrismaClient } from "@prisma/client/edge"; +import { withAccelerate } from "@prisma/extension-accelerate"; +import { sign, verify } from "hono/jwt"; +import { userRouter } from "./user"; + +export const bookRouter = new Hono<{ + Bindings: { + DATABASE_URL: string; + JWT_SECRET: string; + }; + Variables: { + userId: string; + }; +}>(); + +bookRouter.use("/*", async (c, next) => { + const authHeader = c.req.header("authorization") || ""; + try { + const user = await verify(authHeader, c.env.JWT_SECRET); + if (user) { + c.set("userId", user.id + ""); + await next(); + } else { + c.status(403); + return c.json({ + message: "You are not logged in", + }); + } + } catch (e) { + c.status(403); + return c.json({ + message: "You are not logged in", + }); + } +}); + +bookRouter.get("/all", async (c) => { + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const books = await prisma.booked.findMany({ + where: { + userId: c.get("userId"), + }, + }); + return c.json({ books: books }); + } catch (e) { + return c.json({ + message: "Fail to fetch from db", + }); + } +}); + +bookRouter.post("/add", async (c) => { + const body = await c.req.json(); + + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + + try { + const book = await prisma.booked.create({ + data: { + userId: c.get("userId"), + title: body.title, + type: body.type, + description: body.description, + quantity: Number(body.quantity), + rentedId: body.id, + availableTill: body.availableTill, + price: Number(body.price), + }, + }); + return c.json({ + id: book.id, + }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); + +bookRouter.post("/delete", async (c) => { + const body = await c.req.json(); + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const rent = await prisma.rented.delete({ + where: { id: body.id }, + }); + return c.json({ + message: "deleted", + }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); diff --git a/backend/src/routes/profile.ts b/backend/src/routes/profile.ts new file mode 100644 index 0000000..ed789f6 --- /dev/null +++ b/backend/src/routes/profile.ts @@ -0,0 +1,110 @@ +import { Hono } from "hono"; +import { PrismaClient } from "@prisma/client/edge"; +import { withAccelerate } from "@prisma/extension-accelerate"; +import { sign, verify } from "hono/jwt"; +import { userRouter } from "./user"; + +export const profileRouter = new Hono<{ + Bindings: { + DATABASE_URL: string; + JWT_SECRET: string; + }; + Variables: { + userId: string; + }; +}>(); + +profileRouter.use("/*", async (c, next) => { + const authHeader = c.req.header("authorization") || ""; + try { + const user = await verify(authHeader, c.env.JWT_SECRET); + if (user) { + c.set("userId", user.id + ""); + await next(); + } else { + c.status(403); + return c.json({ + message: "You are not logged in", + }); + } + } catch (e) { + c.status(403); + return c.json({ + message: e, + }); + } +}); + +profileRouter.post("/add", async (c) => { + const body = await c.req.json(); + + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + + try { + const profile = await prisma.profile.create({ + data: { + userId: c.get("userId"), + username: body.username, + house_no: body.house_no, + street: body.street, + city_state: body.city_state, + area: body.area, + address: body.address, + phone_num: body.phone_num, + }, + }); + return c.json(profile); + } catch (e) { + return c.json({ + message: e, + }); + } +}); + +profileRouter.get("/all", async (c) => { + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const profile = await prisma.profile.findUnique({ + where: { userId: c.get("userId") }, + }); + return c.json({ profile: profile }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); + +profileRouter.put("/update", async (c) => { + const body = await c.req.json(); + + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + + try { + const profile = await prisma.profile.update({ + where: { userId: c.get("userId") }, + data: { + username: body.username, + house_no: body.house_no, + street: body.street, + city_state: body.city_state, + area: body.area, + address: body.address, + phone_num: body.phone_num, + }, + }); + return c.json({ + message: "created", + }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); diff --git a/backend/src/routes/rent.ts b/backend/src/routes/rent.ts new file mode 100644 index 0000000..3edaa78 --- /dev/null +++ b/backend/src/routes/rent.ts @@ -0,0 +1,129 @@ +import { Hono } from "hono"; +import { PrismaClient } from "@prisma/client/edge"; +import { withAccelerate } from "@prisma/extension-accelerate"; +import { sign, verify } from "hono/jwt"; +import { userRouter } from "./user"; + +export const rentRouter = new Hono<{ + Bindings: { + DATABASE_URL: string; + JWT_SECRET: string; + }; + Variables: { + userId: string; + }; +}>(); + +rentRouter.use("/*", async (c, next) => { + const authHeader = c.req.header("authorization") || ""; + try { + const user = await verify(authHeader, c.env.JWT_SECRET); + if (user) { + c.set("userId", user.id + ""); + await next(); + } else { + c.status(403); + return c.json({ + message: "You are not logged in", + }); + } + } catch (e) { + c.status(403); + return c.json({ + message: "You are not logged in", + }); + } +}); + +rentRouter.get("/all", async (c) => { + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const rents = await prisma.rented.findMany({ + where: { + userId: c.get("userId"), + }, + }); + return c.json({ rents: rents }); + } catch (e) { + return c.json({ + message: "Fail to fetch from db", + }); + } +}); + +rentRouter.post("/add", async (c) => { + const body = await c.req.json(); + + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + + try { + const rent = await prisma.rented.create({ + data: { + userId: c.get("userId"), + title: body.title, + type: body.type, + description: body.description, + quantity: Number(body.quantity), + availibility: true, + price: Number(body.price), + }, + }); + return c.json({ + id: rent.id, + }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); + +rentRouter.put("/update", async (c) => { + const body = await c.req.json(); + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const rent = await prisma.rented.update({ + where: { id: body.id }, + data: { + title: body.title, + type: body.type, + description: body.description, + quantity: Number(body.quantity), + availibility: body.availibility, + price: Number(body.price), + }, + }); + return c.json({ + id: rent.id, + }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); + +rentRouter.post("/delete", async (c) => { + const body = await c.req.json(); + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const rent = await prisma.rented.delete({ + where: { id: body.id }, + }); + return c.json({ + message: "deleted", + }); + } catch (e) { + return c.json({ + message: e, + }); + } +}); diff --git a/backend/src/routes/rentAllRouter.ts b/backend/src/routes/rentAllRouter.ts new file mode 100644 index 0000000..e751431 --- /dev/null +++ b/backend/src/routes/rentAllRouter.ts @@ -0,0 +1,30 @@ +import { Hono } from "hono"; +import { PrismaClient } from "@prisma/client/edge"; +import { withAccelerate } from "@prisma/extension-accelerate"; +import { sign, verify } from "hono/jwt"; + +export const rentAllRouter = new Hono<{ + Bindings: { + DATABASE_URL: string; + JWT_SECRET: string; + }; + Variables: { + userId: string; + }; +}>(); + +rentAllRouter.get("/", async (c) => { + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + try { + const rents = await prisma.rented.findMany(); + return c.json({ + rents: rents, + }); + } catch (e) { + return c.json({ + message: "Fail to fetch from db", + }); + } +}); diff --git a/backend/src/routes/user.ts b/backend/src/routes/user.ts index 347b418..10748ef 100644 --- a/backend/src/routes/user.ts +++ b/backend/src/routes/user.ts @@ -9,10 +9,56 @@ export const userRouter = new Hono<{ JWT_SECRET: string; }; Variables: { - customerId: string; + userId: string; }; }>(); +userRouter.get("/getUser", async(c, next) => { + const authHeader = c.req.header("authorization") || ""; + try { + const user = await verify(authHeader, c.env.JWT_SECRET); + if (user) { + c.set("userId", user.id + ""); + await next(); + } else { + c.status(403); + return c.json({ + message: null + }); + } + } catch (error) { + return c.json({ + message: null + }) + } + +}, async(c) => { + const prisma = new PrismaClient({ + datasourceUrl: c.env.DATABASE_URL, + }).$extends(withAccelerate()); + + try { + const user = await prisma.user.findUnique({ + where: { + id: c.get("userId"), + } + }); + + if(!user) return c.json({ + message: null + }) + + return c.json({ + name: user.name, + email: user.email + }); + } catch (e) { + return c.json({ + message: null + }); + } +}) + userRouter.post("/signup", async (c) => { const body = await c.req.json(); @@ -23,7 +69,7 @@ userRouter.post("/signup", async (c) => { }).$extends(withAccelerate()); try { - const exists = await prisma.customer.findUnique({ + const exists = await prisma.user.findUnique({ where: { email: body.email, }, @@ -50,7 +96,7 @@ userRouter.post("/signup", async (c) => { } try { - const customer = await prisma.customer.create({ + const user = await prisma.user.create({ data: { name: body.name, email: body.email, @@ -59,7 +105,7 @@ userRouter.post("/signup", async (c) => { }); const jwt = await sign( { - id: customer.id, + id: user.id, }, c.env.JWT_SECRET ); @@ -67,7 +113,7 @@ userRouter.post("/signup", async (c) => { return c.json({ status: 200, message: jwt, - name: customer.name, + name: user.name, }); } catch (e) { console.log(e); @@ -88,14 +134,14 @@ userRouter.post("/signin", async (c) => { }).$extends(withAccelerate()); try { - const customer = await prisma.customer.findFirst({ + const user = await prisma.user.findFirst({ where: { email: body.email, password: body.password, }, }); - if (!customer) { + if (!user) { return c.json({ status: 403, message: "Incorrect credentials", @@ -104,7 +150,7 @@ userRouter.post("/signin", async (c) => { const jwt = await sign( { - id: customer.id, + id: user.id, }, c.env.JWT_SECRET ); @@ -112,7 +158,7 @@ userRouter.post("/signin", async (c) => { return c.json({ status: 200, message: jwt, - name: customer.name, + name: user.name, }); } catch (e) { console.log(e); @@ -133,13 +179,13 @@ userRouter.post("/signingoogle", async (c) => { }).$extends(withAccelerate()); try { - const customer = await prisma.customer.findUnique({ + const user = await prisma.user.findUnique({ where: { email: body.email, }, }); - if (!customer) { + if (!user) { return c.json({ status: 403, message: "User does not exists", @@ -148,7 +194,7 @@ userRouter.post("/signingoogle", async (c) => { const jwt = await sign( { - id: customer.id, + id: user.id, }, c.env.JWT_SECRET ); @@ -157,7 +203,7 @@ userRouter.post("/signingoogle", async (c) => { return c.json({ status: 200, message: jwt, - name: customer.name, + name: user.name, }); } catch (e) { console.log(e); @@ -173,9 +219,9 @@ userRouter.put( async (c, next) => { const authHeader = c.req.header("authorization") || ""; try { - const customer = await verify(authHeader, c.env.JWT_SECRET); - if (customer) { - c.set("customerId", customer.id + ""); + const user = await verify(authHeader, c.env.JWT_SECRET); + if (user) { + c.set("userId", user.id + ""); await next(); } else { c.status(403); @@ -202,9 +248,9 @@ userRouter.put( }).$extends(withAccelerate()); try { - const customer = await prisma.customer.update({ + const user = await prisma.user.update({ where: { - id: Number(c.get("customerId")), + id: c.get("userId"), }, data: { password: body.password, @@ -214,7 +260,7 @@ userRouter.put( c.status(200); return c.json({ status: 200, - name: customer.name, + name: user.name, }); } catch (e) { return c.json({ @@ -224,5 +270,3 @@ userRouter.put( } } ); - -//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MX0.6bFcCtTAdwYozlEy0_wxYOGwNlgcTaIIWtRBEUCGcFU diff --git a/backend/wrangler.toml b/backend/wrangler.toml index 72e4edf..18e0316 100644 --- a/backend/wrangler.toml +++ b/backend/wrangler.toml @@ -2,7 +2,7 @@ name = "backend" compatibility_date = "2023-12-01" [vars] -DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlfa2V5IjoiZDM1NGI3YzEtYzczZS00Nzk2LTk2ZjMtZDZjZDI2ODhlYTkwIiwidGVuYW50X2lkIjoiNzdkNzhiYjliYTNkY2NiNDI2MTQ3ZDZmMTcyYjllMTUwNjM4ZjU2ZTA5YWJhNGE5NjlhYWIzNmQ1MmQ0NjBiMCIsImludGVybmFsX3NlY3JldCI6IjFjNDNjNDhhLTg0ODMtNGFlOS05MTdmLTUzZGU0NjhhM2U2MyJ9.JZW_t4Yzh_AOKnXbeUlxGQHC46xOLRPYXoierEQVrGs" +DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlfa2V5IjoiN2QxMzJmNzItYmVhMi00MjVmLTgzOTQtNjA3YzM2NjhlNTk5IiwidGVuYW50X2lkIjoiOTgzOWE1ZDE3ZWMyMGNkMDAzOTcwZGJiNDhjN2QyYjIwNzRhN2MzOTQwNjQxMjZlOGIzZjY0NzE3OGE1NTJkMCIsImludGVybmFsX3NlY3JldCI6IjhmMWEyZjNlLTlmOTUtNDAwMS1iNTNlLWMwNDVkMDYyMTcyMyJ9.o9FQyqPVnU299nbFNCUC7TxuS8zNv29IOk8t9IEJI_c" JWT_SECRET="siddhantkotak20045" # [[kv_namespaces]] diff --git a/frontend/src/Components/DropDown.tsx b/frontend/src/Components/DropDown.tsx index 38934b3..0401d4f 100644 --- a/frontend/src/Components/DropDown.tsx +++ b/frontend/src/Components/DropDown.tsx @@ -15,7 +15,7 @@ import { useNavigate } from "react-router-dom"; // } const DropDown = () => { - const { username, setLoggedIn } = useContext(AppContext) as Context; + const { logUser, setLoggedIn } = useContext(AppContext) as Context; const navigate = useNavigate(); return ( @@ -26,11 +26,11 @@ const DropDown = () => {
{/* src = userImage */}
- {username[0].toUpperCase()} + {logUser.name[0].toUpperCase()}
{/* userName */}

- {username} + {logUser.name}


diff --git a/frontend/src/Components/GoogleButton.tsx b/frontend/src/Components/GoogleButton.tsx index 0da1f02..2688e06 100644 --- a/frontend/src/Components/GoogleButton.tsx +++ b/frontend/src/Components/GoogleButton.tsx @@ -37,12 +37,10 @@ const GoogleButton = ({ type }: { type: "SignUp" | "Login" }) => { setUsername(data.name); setLoggedIn(true); console.log("inside signup"); - localStorage.setItem("loggedIn", "" + true); navigate("/setpassword"); } else if (data.status == 403) { setLoggedIn(true); localStorage.setItem("token", data.message); - localStorage.setItem("loggedIn", "" + true); console.log( "in the signup but in status 403 and the username is : ", data.name @@ -77,7 +75,6 @@ const GoogleButton = ({ type }: { type: "SignUp" | "Login" }) => { name: data.name, }); console.log("inside login input /signingoogle"); - localStorage.setItem("loggedIn", "" + true); localStorage.setItem("token", data.message); navigate("/"); } else alert(data.message); diff --git a/frontend/src/Components/LogInInput.tsx b/frontend/src/Components/LogInInput.tsx index 94a15ad..4f072e7 100644 --- a/frontend/src/Components/LogInInput.tsx +++ b/frontend/src/Components/LogInInput.tsx @@ -28,9 +28,8 @@ const LogInInput = () => { const data = res.data; if (data.status == 200) { console.log("in login :", res.data); - localStorage.setItem("token", data.token); + localStorage.setItem("token", data.message); setLoggedIn(true); - localStorage.setItem("loggedIn", "" + true); setLogUser({ email: postInputs.email, name: data.name, diff --git a/frontend/src/Components/Navbar.tsx b/frontend/src/Components/Navbar.tsx index 4e1b7f0..3243f53 100644 --- a/frontend/src/Components/Navbar.tsx +++ b/frontend/src/Components/Navbar.tsx @@ -9,36 +9,11 @@ import { IoSearch } from "react-icons/io5"; import { IoCartOutline } from "react-icons/io5"; import DropDown from "./DropDown"; -const Photo = () => { - const { username, dropdown, setDropdown, logUser } = useContext( - AppContext - ) as Context; - return ( - - ); -}; - const Navbar = () => { - const { loggedIn, username, dropdown, setDropdown } = useContext( - AppContext - ) as Context; + const { loggedIn, dropdown } = useContext(AppContext) as Context; const [search, setSearch] = useState(""); const navigate = useNavigate(); - const [loggedInl, setLoggedInl] = useState(() => { - return localStorage.getItem("loggedIn") === "true"; - }); - function handleKey(e: React.KeyboardEvent) { if (e.key == "Enter") { Search(search); @@ -105,7 +80,7 @@ const Navbar = () => {
- {loggedInl ? ( + {loggedIn ? ( Photo() ) : ( <> @@ -129,4 +104,21 @@ const Navbar = () => { ); }; +const Photo = () => { + const { dropdown, setDropdown, logUser } = useContext(AppContext) as Context; + return ( + + ); +}; + export default Navbar; diff --git a/frontend/src/Components/SignUpInput.tsx b/frontend/src/Components/SignUpInput.tsx index ea78f46..5f58544 100644 --- a/frontend/src/Components/SignUpInput.tsx +++ b/frontend/src/Components/SignUpInput.tsx @@ -36,7 +36,6 @@ const SignUpInput = () => { if (data.status == 200) { localStorage.setItem("token", data.message); setLoggedIn(true); - localStorage.setItem("loggedIn", "" + true); setUsername(data.name); navigate("/"); } else if (data.status == 403) { diff --git a/frontend/src/Context/UseContext.tsx b/frontend/src/Context/UseContext.tsx index 773c2ef..3624f02 100644 --- a/frontend/src/Context/UseContext.tsx +++ b/frontend/src/Context/UseContext.tsx @@ -1,4 +1,5 @@ -import { createContext, useState } from "react"; +import axios from "axios"; +import { createContext, useEffect, useState } from "react"; type User = { name: string; @@ -52,6 +53,8 @@ export interface Context { setRented: React.Dispatch>; booked: Booked; setBooked: React.Dispatch>; + addProfile: boolean; + setAddProfile: React.Dispatch>; } export const AppContext = createContext(null); @@ -59,13 +62,11 @@ export const AppContext = createContext(null); const AppContextProvider: React.FC<{ children: React.ReactNode }> = ({ children, }) => { + const [addProfile, setAddProfile] = useState(false); const [loggedIn, setLoggedIn] = useState(false); const [username, setUsername] = useState(""); const [dropdown, setDropdown] = useState(false); - const [logUser, setLogUser] = useState({ - name: "", - email: "", - }); + const [logUser, setLogUser] = useState({ name: "", email: "" }); const [profile, setProfile] = useState({ username: "", house_no: "", @@ -95,6 +96,36 @@ const AppContextProvider: React.FC<{ children: React.ReactNode }> = ({ price: 0, }); + async function sendRequest() { + const BACKEND_URL = import.meta.env.VITE_BACKEND_URL; + try { + //jwt add + const res = await axios.get(`${BACKEND_URL}/api/v1/user/getUser`, { + headers: { + Authorization: `${localStorage.getItem("token")}`, + }, + }); + setLogUser({ + name: res.data.name, + email: res.data.email, + }); + if (res.data.message !== null) { + setLoggedIn(true); + } + } catch (error) { + console.log("error in fetching the data of jwt in useContext: "); + console.log(error); + } + } + + useEffect(() => { + if (localStorage.getItem("token") !== null) { + sendRequest(); + } else { + setLoggedIn(false); + } + }, []); + return ( = ({ setRented, booked, setBooked, + addProfile, + setAddProfile, }} > {children} diff --git a/frontend/src/Pages/EditProfile.tsx b/frontend/src/Pages/EditProfile.tsx index af7f32f..2bf01a8 100644 --- a/frontend/src/Pages/EditProfile.tsx +++ b/frontend/src/Pages/EditProfile.tsx @@ -6,36 +6,33 @@ import axios from "axios"; import { useNavigate } from "react-router-dom"; const username: string = "yash21234"; -const house_no: string = "C-1102"; -const street: string = "Ujala Circle"; -const area: string = "Sarkhej Circle"; -const city_state: string = "Ahmedabad,Guajarat"; -const phone_num: string = "9898134321"; const EditProfile = () => { const navigate = useNavigate(); - const { profile, setProfile, logUser } = useContext(AppContext) as Context; + const { profile, setProfile, logUser, addProfile } = useContext( + AppContext + ) as Context; const name: string = logUser.name; const email: string = logUser.email; const BACKEND_URL = import.meta.env.VITE_BACKEND_URL; async function sendRequest() { - console.log( - "in the edit profile send request method and the jwt is : ", - localStorage.getItem("token") - ); try { - const res = await axios.post( - `${BACKEND_URL}/api/v1/profile/add`, - profile, - { + if (addProfile) { + await axios.post(`${BACKEND_URL}/api/v1/profile/add}`, profile, { headers: { Authorization: localStorage.getItem("token"), }, - } - ); - console.log("res data"); - console.log(res.data); + }); + setProfile(profile); + } else { + await axios.put(`${BACKEND_URL}/api/v1/profile/update`, profile, { + headers: { + Authorization: localStorage.getItem("token"), + }, + }); + setProfile(profile); + } navigate("/"); } catch (e) { alert("Error while login in"); @@ -43,7 +40,6 @@ const EditProfile = () => { } function submitHandler(e: React.FormEvent) { - console.log("inside the edit profile and this is the profile", profile); e.preventDefault(); sendRequest(); } @@ -94,7 +90,7 @@ const EditProfile = () => { { setProfile({ ...profile, phone_num: e.target.value }); }} @@ -106,7 +102,7 @@ const EditProfile = () => { { setProfile({ ...profile, house_no: e.target.value }); }} @@ -118,7 +114,7 @@ const EditProfile = () => { { setProfile({ ...profile, street: e.target.value }); }} @@ -130,7 +126,7 @@ const EditProfile = () => { { setProfile({ ...profile, area: e.target.value }); }} @@ -142,7 +138,7 @@ const EditProfile = () => { { setProfile({ ...profile, city_state: e.target.value }); }} diff --git a/frontend/src/Pages/UserInfo.tsx b/frontend/src/Pages/UserInfo.tsx index 47b6555..73b5b23 100644 --- a/frontend/src/Pages/UserInfo.tsx +++ b/frontend/src/Pages/UserInfo.tsx @@ -6,12 +6,14 @@ import { useNavigate } from "react-router-dom"; const UserInfo: React.FC = () => { const navigate = useNavigate(); - const { profile, setProfile, logUser } = useContext(AppContext) as Context; + const { profile, setProfile, logUser, setAddProfile } = useContext( + AppContext + ) as Context; const BACKEND_URL = import.meta.env.VITE_BACKEND_URL; async function sendRequest() { + console.log(localStorage.getItem("token")); try { - console.log(localStorage.getItem("token")); const res = await axios.get(`${BACKEND_URL}/api/v1/profile/all`, { headers: { Authorization: localStorage.getItem("token"), @@ -80,6 +82,7 @@ const UserInfo: React.FC = () => {