Skip to content

Commit

Permalink
Merge pull request #106 from Somnath-Chattaraj/test1111
Browse files Browse the repository at this point in the history
test1111
  • Loading branch information
Somnath-Chattaraj authored Oct 10, 2024
2 parents e057952 + 4f152df commit 47299db
Show file tree
Hide file tree
Showing 11 changed files with 372 additions and 1 deletion.
17 changes: 17 additions & 0 deletions backend/package-lock.json

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

2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@types/cors": "^2.8.17",
"@types/jsonwebtoken": "^9.0.6",
"@types/nodemailer": "^6.4.15",
"@types/otp-generator": "^4.0.2",
"@types/ws": "^8.5.12",
"academic-email-verifier": "^3.1.0",
"bcrypt": "^5.1.1",
Expand All @@ -39,6 +40,7 @@
"jsonwebtoken": "^9.0.2",
"nodemailer": "^6.9.14",
"nodemon": "^3.1.4",
"otp-generator": "^4.0.1",
"prettier": "^3.3.3",
"ws": "^8.18.0",
"zod": "^3.23.8"
Expand Down
19 changes: 19 additions & 0 deletions backend/prisma/migrations/20241010094547_dev/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "pic" TEXT DEFAULT 'https://i1.sndcdn.com/artworks-000338788569-fxot50-t500x500.jpg';

-- CreateTable
CREATE TABLE "Otp" (
"id" SERIAL NOT NULL,
"otp" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,

CONSTRAINT "Otp_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE INDEX "Otp_userId_idx" ON "Otp"("userId");

-- AddForeignKey
ALTER TABLE "Otp" ADD CONSTRAINT "Otp_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("user_id") ON DELETE RESTRICT ON UPDATE CASCADE;
13 changes: 13 additions & 0 deletions backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,21 @@ model User {
chatRooms ChatRoom[] @relation("UserChatRooms")
sentMessages Message[] @relation("SentMessages")
Like Like[]
Otp Otp[]
}

model Otp {
id Int @id @default(autoincrement())
otp String
userId String
user User @relation(fields: [userId], references: [user_id])
createdAt DateTime @default(now())
expiresAt DateTime
@@index([userId])
}


model College {
college_id String @id @default(uuid())
name String
Expand Down
92 changes: 92 additions & 0 deletions backend/src/controllers/otpController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import asyncHandler from "express-async-handler";
import otp from "otp-generator";
import prisma from "../lib/prisma";
import sendMail from "../mail/sendMail";
import bcrypt from "bcrypt";

export const otpGenerator = asyncHandler(async (req: any, res: any) => {
const {email} = req.body;

const otpCode = otp.generate(6, { upperCaseAlphabets: false, specialChars: false });
try {
const user = await prisma.user.findFirst({
where: {
email,
},
});
if (!user) {
return res.status(404).json({ message: "User not found" });
}
const response = await prisma.otp.create({
data: {
otp: otpCode,
user: {
connect: {
email,
},
},
expiresAt: new Date(Date.now() + 10 * 60 * 1000),
},
});
const htmlContent = `<h1>Your OTP is ${otpCode}</h1>`;
await sendMail(htmlContent, email);
res.status(200).json({ message: "OTP generated successfully and email sent" });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error in generating OTP" });
}
});


export const verifyOtp = asyncHandler(async (req: any, res: any) => {
const { otp, email } = req.body;

try {
const otpData = await prisma.otp.findFirst({
where: {
otp: otp,

user: {
email,
},
expiresAt: {
gte: new Date(),
},
},
});

if (!otpData) {
return res.status(400).json({ message: "Invalid OTP" });
}

await prisma.otp.delete({
where: {
id: otpData.id,
},
});

res.status(200).json({ message: "OTP verified successfully" });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error in verifying OTP" });
}
});

export const changePassword = asyncHandler(async (req: any, res: any) => {
const {email, password} = req.body;
const hashedPassword = await bcrypt.hash(password, 8);
try {
const response = await prisma.user.update({
where: {
email,
},
data: {
password: hashedPassword,
},
});
res.status(200).json({ message: "Password changed successfully" });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Error in changing password" });
}
});
1 change: 1 addition & 0 deletions backend/src/controllers/userControllers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,7 @@ const updateDetails = asyncHandler(async (req: Request, res: Response) => {
},
data: {
username,
// @ts-ignore
pic,
},
});
Expand Down
2 changes: 2 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import reviewRoutes from "./routes/reviewRoutes";
import ratingRoutes from "./routes/ratingRoute";
import postsRoutes from "./routes/postsRoutes";
import roomRouter from "./routes/roomRoutes";
import Otprouter from "./routes/otpRoute";

// import { getCommunities } from "./controllers/postController";

Expand Down Expand Up @@ -39,6 +40,7 @@ app.use("/api/rating", ratingRoutes);
app.use("/api/chat", chatRoutes); // Use the chat routes
app.use("/api/post", postsRoutes);
app.use("/api/room", roomRouter);
app.use("/api/otp", Otprouter);
// app.get("/api/post/communities", getCommunities);
app.get("/api/logout", (req: Request, res: Response) => {
res.clearCookie("Authorization").json({ message: "Logged out successfully" });
Expand Down
10 changes: 10 additions & 0 deletions backend/src/routes/otpRoute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express from "express";
import { calAvgRating } from "../controllers/ratingController";
import { changePassword, otpGenerator, verifyOtp } from "../controllers/otpController";

const Otprouter = express.Router();

Otprouter.post('/' ,otpGenerator);
Otprouter.get('/verify',verifyOtp);
Otprouter.post('/change', changePassword);
export default Otprouter;
3 changes: 2 additions & 1 deletion frontend/src/components/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import { FcGoogle } from "react-icons/fc"; // Google icon
import { FaGithub } from "react-icons/fa"; // GitHub icon
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import { auth, googleProvider, githubProvider } from "../firebase.js";
import { signInWithPopup } from "firebase/auth";
import { InfinitySpin } from "react-loader-spinner";
Expand Down Expand Up @@ -221,6 +221,7 @@ const LoginPage = () => {
>
Login
</Button>
<Link className="text-center" to='/forgetPassword'>Forgot Password?</Link>
<Button
leftIcon={<FcGoogle />}
colorScheme="gray"
Expand Down
Loading

0 comments on commit 47299db

Please sign in to comment.