Skip to content

Commit

Permalink
Fix backend
Browse files Browse the repository at this point in the history
  • Loading branch information
tanish35 committed Oct 15, 2024
1 parent f992c31 commit 4748e44
Show file tree
Hide file tree
Showing 10 changed files with 311 additions and 11 deletions.
108 changes: 108 additions & 0 deletions backend/dist/controllers/otpController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.changePassword = exports.verifyOtp = exports.otpGenerator = void 0;
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const otp_generator_1 = __importDefault(require("otp-generator"));
const prisma_1 = __importDefault(require("../lib/prisma"));
const sendMail_1 = __importDefault(require("../mail/sendMail"));
const bcrypt_1 = __importDefault(require("bcrypt"));
exports.otpGenerator = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { email } = req.body;
const otpCode = otp_generator_1.default.generate(6, {
upperCaseAlphabets: false,
specialChars: false,
});
try {
const user = yield prisma_1.default.user.findFirst({
where: {
email,
},
});
if (!user) {
return res.status(404).json({ message: "User not found" });
}
if (!user.emailVerified) {
return res.status(400).json({ message: "Email not verified" });
}
const response = yield prisma_1.default.otp.create({
data: {
otp: otpCode,
user: {
connect: {
email,
},
},
expiresAt: new Date(Date.now() + 10 * 60 * 1000),
},
});
const htmlContent = `<h1>Your OTP is ${otpCode}</h1>`;
yield (0, sendMail_1.default)(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" });
}
}));
exports.verifyOtp = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { otp, email } = req.body;
try {
const otpData = yield prisma_1.default.otp.findFirst({
where: {
otp: otp,
user: {
email,
},
expiresAt: {
gte: new Date(),
},
},
});
if (otpData === null) {
return res.status(404).json({ message: "Invalid OTP" });
}
res.status(200).json({ message: "OTP verified successfully" });
// await prisma.otp.delete({
// where: {
// id: otpData.id,
// },
// });
}
catch (error) {
console.error(error);
res.status(500).json({ message: "Error in verifying OTP" });
}
}));
exports.changePassword = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { email, password } = req.body;
const hashedPassword = yield bcrypt_1.default.hash(password, 8);
try {
const response = yield prisma_1.default.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" });
}
}));
109 changes: 108 additions & 1 deletion backend/dist/controllers/postController.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAllCommunities = exports.searchPosts = exports.unlikePost = exports.postLiked = exports.createComment = exports.fetchSinglePost = exports.likePost = exports.fetchPosts = exports.createPost = exports.getCommunities = void 0;
exports.deleteComment = exports.deletePost = exports.getAllCommunities = exports.searchPosts = exports.unlikePost = exports.postLiked = exports.createComment = exports.fetchSinglePost = exports.likePost = exports.fetchPosts = exports.createPost = exports.getCommunities = void 0;
const express_async_handler_1 = __importDefault(require("express-async-handler"));
const prisma_1 = __importDefault(require("../lib/prisma"));
const fuse_js_1 = __importDefault(require("fuse.js"));
const sendMail_1 = __importDefault(require("../mail/sendMail"));
// @ts-ignore
const searchPosts = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { query } = req.body;
Expand All @@ -32,6 +33,12 @@ const searchPosts = (0, express_async_handler_1.default)((req, res) => __awaiter
name: true,
},
},
User: {
select: {
username: true,
pic: true,
},
},
},
});
const fuse = new fuse_js_1.default(posts, {
Expand Down Expand Up @@ -135,6 +142,11 @@ const fetchPosts = (0, express_async_handler_1.default)((req, res) => __awaiter(
pic: true,
},
},
_count: {
select: {
Comments: true,
},
},
},
take: postsPerPage,
skip: offset,
Expand Down Expand Up @@ -202,6 +214,7 @@ const fetchSinglePost = (0, express_async_handler_1.default)((req, res) => __awa
User: {
select: {
username: true,
pic: true,
},
},
Comments: {
Expand All @@ -212,6 +225,7 @@ const fetchSinglePost = (0, express_async_handler_1.default)((req, res) => __awa
User: {
select: {
username: true,
pic: true,
},
},
},
Expand All @@ -225,6 +239,30 @@ const fetchSinglePost = (0, express_async_handler_1.default)((req, res) => __awa
}));
exports.fetchSinglePost = fetchSinglePost;
// @ts-ignore
const deletePost = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { postId } = req.body;
const post = yield prisma_1.default.post.findUnique({
select: {
User: {
select: {
user_id: true,
},
},
},
where: { post_id: postId },
});
// @ts-ignore
const user_id = req.user.user_id;
if (!post) {
return res.status(404).json({ message: "Post not found" });
}
if (post.User.user_id !== user_id) {
return res.status(401).json({ message: "Unauthorized" });
}
return res.status(200).json({ message: "Post deleted" });
}));
exports.deletePost = deletePost;
// @ts-ignore
const createComment = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { postId, content } = req.body;
// @ts-ignore
Expand All @@ -245,10 +283,79 @@ const createComment = (0, express_async_handler_1.default)((req, res) => __await
post_id: postId,
},
});
const post = yield prisma_1.default.post.findUnique({
where: { post_id: postId },
select: {
title: true,
User: {
select: {
email: true,
user_id: true,
},
},
},
});
if (!post) {
return res.status(404).json({ message: "Post not found" });
}
if (post.User.user_id === user_id) {
return res.status(201).json({ comment });
}
const email = post.User.email;
const postTitle = post.title;
const commentContent = comment.content;
const commentAuthor = user.username;
const htmlContent = `
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f4f4f4; border-radius: 10px;">
<h2 style="color: #4CAF50; text-align: center;">New Comment on Your Post</h2>
<div style="background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
<h3 style="color: #333;">Post Title: ${postTitle}</h3>
<p style="color: #666; font-size: 14px;">A new comment has been added to your post:</p>
<blockquote style="background-color: #f9f9f9; border-left: 4px solid #4CAF50; padding: 10px 20px; margin: 10px 0; color: #555;">
${commentContent}
</blockquote>
<p style="color: #666; font-size: 14px;">Commented by: <strong>${commentAuthor}</strong></p>
<a href="https://campusify.site/posts/${postId}" style="display: inline-block; margin-top: 20px; background-color: #4CAF50; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;">View Post</a>
</div>
<footer style="text-align: center; margin-top: 20px; color: #999; font-size: 12px;">
<p>Campusify</p>
<p><a href="https://campusify.site" style="color: #4CAF50;">Visit our website</a></p>
</footer>
</div>
`;
(0, sendMail_1.default)(htmlContent, email, "New Comment on Your Post");
return res.status(201).json({ comment });
}));
exports.createComment = createComment;
// @ts-ignore
const deleteComment = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { commentId } = req.body;
const comment = yield prisma_1.default.comment.findUnique({
select: {
User: {
select: {
user_id: true,
},
},
},
where: { comment_id: commentId },
});
// @ts-ignore
const user_id = req.user.user_id;
if (!comment) {
return res.status(404).json({ message: "Comment not found" });
}
if (comment.User.user_id !== user_id) {
return res.status(401).json({ message: "Unauthorized" });
}
return res.status(200).json({ message: "Comment deleted" });
}));
exports.deleteComment = deleteComment;
// @ts-ignore
const postLiked = (0, express_async_handler_1.default)((req, res) => __awaiter(void 0, void 0, void 0, function* () {
const { postId } = req.body;
// @ts-ignore
Expand Down
7 changes: 7 additions & 0 deletions backend/dist/controllers/routeControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ const searchRoom = (0, express_async_handler_1.default)((req, res) => __awaiter(
// @ts-ignore
const user_id = req.user.user_id;
const rooms = yield prisma_1.default.chatRoom.findMany({
where: {
users: {
some: {
user_id
},
},
},
select: {
id: true,
users: {
Expand Down
5 changes: 4 additions & 1 deletion backend/dist/controllers/userControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ const googleSignInOrSignUp = (0, express_async_handler_1.default)(
sameSite: "lax",
});
const username = user.username;
res.status(200).json({ isCollegeEmail, username });
const userId = user.user_id;
res.status(200).json({ isCollegeEmail, username, userId });
}));
exports.googleSignInOrSignUp = googleSignInOrSignUp;
const githubSignInOrSignUp = (0, express_async_handler_1.default)(
Expand Down Expand Up @@ -317,6 +318,7 @@ const getCurrentUserDetails = (0, express_async_handler_1.default)((req, res) =>
user_id: true,
email: true,
username: true,
pic: true,
userCourses: {
select: {
Course: {
Expand Down Expand Up @@ -596,6 +598,7 @@ const updateDetails = (0, express_async_handler_1.default)((req, res) => __await
},
data: {
username,
// @ts-ignore
pic,
},
});
Expand Down
11 changes: 7 additions & 4 deletions backend/dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,16 @@ const reviewRoutes_1 = __importDefault(require("./routes/reviewRoutes"));
const ratingRoute_1 = __importDefault(require("./routes/ratingRoute"));
const postsRoutes_1 = __importDefault(require("./routes/postsRoutes"));
const roomRoutes_1 = __importDefault(require("./routes/roomRoutes"));
const otpRoute_1 = __importDefault(require("./routes/otpRoute"));
// import { getCommunities } from "./controllers/postController";
const app = (0, express_1.default)();
app.use(express_1.default.json());
const corsOptions = {
origin: [
"http://localhost:3001",
"https://app-statuscode1.wedevelopers.online",
"http://localhost:5173",
"https://www.campusify.site/",
"https://app.campusify.site/",
],
credentials: true,
};
Expand All @@ -35,10 +37,11 @@ app.use("/api/review", reviewRoutes_1.default);
app.use("/api/rating", ratingRoute_1.default);
app.use("/api/chat", chatRoutes_1.default); // Use the chat routes
app.use("/api/post", postsRoutes_1.default);
app.use('/api/room', roomRoutes_1.default);
app.use("/api/room", roomRoutes_1.default);
app.use("/api/otp", otpRoute_1.default);
// app.get("/api/post/communities", getCommunities);
app.get('/api/logout', (req, res) => {
res.clearCookie('Authorization').json({ message: 'Logged out successfully' });
app.get("/api/logout", (req, res) => {
res.clearCookie("Authorization").json({ message: "Logged out successfully" });
});
app.get("/", (req, res) => {
res.send("Backend is running");
Expand Down
10 changes: 5 additions & 5 deletions backend/dist/mail/sendMail.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
const nodemailer_1 = __importDefault(require("nodemailer"));
const sendMail = (htmlContent, receiverEmail) => {
const sendMail = (htmlContent, receiverEmail, subject = "Verification Email") => {
const port = process.env.SMTP_PORT;
const host = process.env.SMTP_HOST;
const senderEmail = process.env.SMTP_EMAIL;
const password = process.env.SMTP_PASSWORD;
let transporter = nodemailer_1.default.createTransport({
// @ts-ignore
host: 'smtp.gmail.com',
host: "smtp.gmail.com",
port: port,
secure: true,
auth: {
Expand All @@ -22,15 +22,15 @@ const sendMail = (htmlContent, receiverEmail) => {
let mailOptions = {
from: `"Campus-Chatter Admin" <${senderEmail}>`,
to: receiverEmail,
subject: 'OTP Verification',
subject: subject,
text: htmlContent,
html: htmlContent,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log('Error while sending email:', error);
return console.log("Error while sending email:", error);
}
console.log('Email sent successfully:', info.response);
// console.log('Email sent successfully:', info.response);
});
};
exports.default = sendMail;
12 changes: 12 additions & 0 deletions backend/dist/routes/otpRoute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const otpController_1 = require("../controllers/otpController");
const Otprouter = express_1.default.Router();
Otprouter.post('/', otpController_1.otpGenerator);
Otprouter.post('/verify', otpController_1.verifyOtp);
Otprouter.post('/change', otpController_1.changePassword);
exports.default = Otprouter;
Loading

0 comments on commit 4748e44

Please sign in to comment.