Skip to content
Closed
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
5 changes: 2 additions & 3 deletions backend/controllers/botController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable no-undef */
const { genRes } = require("../utils/botService");
import { genRes } from "../utils/botService.js";

const returnResponse = async (req, res) => {
try {
Expand All @@ -13,4 +12,4 @@ const returnResponse = async (req, res) => {
}
};

module.exports = returnResponse;
export default returnResponse;
141 changes: 141 additions & 0 deletions backend/controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import bcrypt from 'bcryptjs';
import { PrismaClient } from '@prisma/client';
import { generateToken } from '../utils/jwt.js';


const prisma = new PrismaClient();


export const registerUser = async(req,res)=>{
try {
const {email,password,firstName,lastName} = req.body

if(!email || !password || !firstName || !lastName){
return res.status(400).json({
success:false,
message:"Please provide all the fields"
})
}
const existingUser = await prisma.user.findUnique({
where:{email}
})

if(existingUser){
return res.status(400).json({
success:false,
message:"User with this email already exists"
})
}
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password,salt)
const user = await prisma.user.create({
data:{
firstName,
lastName,
email,
password:hashedPassword
}
})
const token = generateToken(user.id)
const {password:_, ...userResponse} = user

Check warning on line 40 in backend/controllers/userController.js

View workflow job for this annotation

GitHub Actions / build (18.x)

'_' is assigned a value but never used

Check warning on line 40 in backend/controllers/userController.js

View workflow job for this annotation

GitHub Actions / build (20.x)

'_' is assigned a value but never used
res.status(201).json({
success:true,
data:{
user:userResponse,
token
},
message:"Registration Successfull"
})
} catch (error) {
console.error("Register error:",error)
res.status(500).json({
success:false,
message:"Server error during registration",
error:error.message
})
}
}

export const login = async(req,res)=>{
try {
const {email,password} = req.body
if(!email || !password){
return res.status(400).json({
success:false,
message:"Please provide email and password"
})
}
const user = await prisma.user.findUnique({
where:{
email
}
})
if(!user){
return res.status(401).json({
success: false,
message:"Invalid email or password"
})
}
const isPasswordValid = await bcrypt.compare(password,user.password)
if(!isPasswordValid){
return res.status(401).json({
success:false,
message:"Invalid password"
})
}
const token = generateToken(user.id)
const {password:_,...userResponse} = user

Check warning on line 87 in backend/controllers/userController.js

View workflow job for this annotation

GitHub Actions / build (18.x)

'_' is assigned a value but never used

Check warning on line 87 in backend/controllers/userController.js

View workflow job for this annotation

GitHub Actions / build (20.x)

'_' is assigned a value but never used
res.status(200).json({
success:true,
data:{
user:userResponse,
token
},
message:"Login Successfull"
})
} catch (error) {
console.error("Login Error",error)
res.status(500).json({
success:false,
message:"Server error during login",
error:error.message
})
}
}

export const getCurrentUser = async(req,res)=>{
try {
const user = await prisma.user.findUnique({
where:{
id:req.user.id
},
select:{
id:true,
firstName:true,
lastName:true,
email:true,
type:true,
createdAt:true,
updatedAt:true
}
})
if(!user){
return res.status(404).json({
success:false,
message:"User not found"
})
}
res.status(200).json({
success:true,
data:{user},
message:"User retrieved successfully"
})
} catch (error) {
console.error("Get current user error",error)
res.status(500).json({
success:false,
message:"Server error",
error:error.message
})
}
}
15 changes: 8 additions & 7 deletions backend/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
/* eslint-disable no-undef */
const express = require("express");
require("dotenv").config();
const botRouter = require("./routes/botRoutes");
const cors = require("cors");
import express from "express";
import dotenv from "dotenv";
import botRouter from "./routes/botRoutes.js";
import cors from "cors";
import userRoutes from "./routes/userRoutes.js"
dotenv.config();

const app = express();
app.use(
cors({
origin: process.env.FRONTEND_URL || "http://localhost:5173",

Check failure on line 11 in backend/index.js

View workflow job for this annotation

GitHub Actions / build (18.x)

'process' is not defined

Check failure on line 11 in backend/index.js

View workflow job for this annotation

GitHub Actions / build (20.x)

'process' is not defined
credentials: true,
methods: ["GET", "POST", "PATCH", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);
const port = process.env.SERVER_PORT || 3000;

Check failure on line 17 in backend/index.js

View workflow job for this annotation

GitHub Actions / build (18.x)

'process' is not defined

Check failure on line 17 in backend/index.js

View workflow job for this annotation

GitHub Actions / build (20.x)

'process' is not defined

app.use(express.json());

app.use("/bot", botRouter);

app.use("/api/bot", botRouter);
app.use("/api/auth",userRoutes)
app.get("/", (req, res) => {
res.send("Backend is Running!");
});
Expand Down
67 changes: 67 additions & 0 deletions backend/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import jwt from 'jsonwebtoken'
import { PrismaClient } from '@prisma/client'


const prisma = new PrismaClient()

export const protect = async(req,res,next)=>{
try {
let token
if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
token = req.headers.authorization.split(' ')[1]
}
if(!token){
return res.status(401).json({
success:false,
message:"Not authorized, no token provided"
})
}
const decoded = jwt.verify(token,process.env.JWT_SECRET)

Check failure on line 19 in backend/middleware/authMiddleware.js

View workflow job for this annotation

GitHub Actions / build (18.x)

'process' is not defined

Check failure on line 19 in backend/middleware/authMiddleware.js

View workflow job for this annotation

GitHub Actions / build (20.x)

'process' is not defined

//Get user from token
const user = await prisma.user.findUnique({
where:{
id:decoded.id
},
select:{
id:true,
firstName:true,
lastName:true,
email:true,
type:true,
createdAt:true,
updatedAt:true
}
})
if(!user){
return res.status(401).json({
success:false,
message:"User not found"
})
}
req.user = user
next();
} catch (error) {
console.error('Auth middleware error:', error);

if (error.name === 'JsonWebTokenError') {
return res.status(401).json({
success: false,
message: 'Invalid token',
});
}

if (error.name === 'TokenExpiredError') {
return res.status(401).json({
success: false,
message: 'Token expired',
});
}

res.status(401).json({
success: false,
message: 'Not authorized',
error: error.message,
});
}
}
28 changes: 28 additions & 0 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
Expand All @@ -13,6 +14,11 @@
"dependencies": {
"@google/genai": "^1.27.0",
"@prisma/client": "^6.18.0",
"bcrypt": "^6.0.0",
"bcryptjs": "^3.0.2",
"body-parser": "^2.2.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0"
},
Expand Down
10 changes: 0 additions & 10 deletions backend/prisma/migrations/20251020103625_init/migration.sql

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
/*
Warnings:

- You are about to drop the `Product` table. If the table is not empty, all the data it contains will be lost.

*/
-- CreateEnum
CREATE TYPE "Gender" AS ENUM ('male', 'female', 'other');

-- CreateEnum
CREATE TYPE "UserType" AS ENUM ('ADMIN', 'USER', 'SELLER');

-- DropTable
DROP TABLE "public"."Product";

-- CreateTable
CREATE TABLE "User" (
"id" SERIAL NOT NULL,
Expand Down
23 changes: 23 additions & 0 deletions backend/prisma/migrations/20251101104032_updated/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
Warnings:

- You are about to drop the column `addresses` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `dob` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `gender` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `name` on the `User` table. All the data in the column will be lost.
- You are about to drop the column `phone` on the `User` table. All the data in the column will be lost.
- Added the required column `firstName` to the `User` table without a default value. This is not possible if the table is not empty.
- Added the required column `lastName` to the `User` table without a default value. This is not possible if the table is not empty.

*/
-- DropIndex
DROP INDEX "public"."User_phone_key";

-- AlterTable
ALTER TABLE "User" DROP COLUMN "addresses",
DROP COLUMN "dob",
DROP COLUMN "gender",
DROP COLUMN "name",
DROP COLUMN "phone",
ADD COLUMN "firstName" TEXT NOT NULL,
ADD COLUMN "lastName" TEXT NOT NULL;
7 changes: 2 additions & 5 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@ datasource db {

model User {
id Int @id @default(autoincrement())
name String
firstName String
lastName String
email String @unique
password String
phone String? @unique
gender Gender?
dob DateTime?
addresses Json?
type UserType @default(USER)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
10 changes: 4 additions & 6 deletions backend/routes/botRoutes.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
/* eslint-disable no-undef */
const express = require("express");
const returnResponse = require("../controllers/botController");
import express from "express";
import returnResponse from "../controllers/botController.js";

const botRouter = express.Router();

botRouter.post("/", returnResponse);

module.exports = {
botRouter
};
export default botRouter;
Loading
Loading