diff --git a/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx b/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx
index e329a81..77666c2 100644
--- a/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx
+++ b/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx
@@ -1,5 +1,10 @@
-import { faMagnifyingGlass, faPhone, faUser, faVideo } from '@fortawesome/free-solid-svg-icons';
-import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import {
+ faMagnifyingGlass,
+ faPhone,
+ faUser,
+ faVideo,
+} from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
const ChatInfoButtons = () => {
return (
diff --git a/client/src/pages/Home/MessageComponents/ChatMenu.jsx b/client/src/pages/Home/MessageComponents/ChatMenu.jsx
index d0ace12..24cb610 100644
--- a/client/src/pages/Home/MessageComponents/ChatMenu.jsx
+++ b/client/src/pages/Home/MessageComponents/ChatMenu.jsx
@@ -1,5 +1,10 @@
-import { faCircleInfo, faPhone, faVideo, faX } from '@fortawesome/free-solid-svg-icons';
-import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import {
+ faCircleInfo,
+ faPhone,
+ faVideo,
+ faX,
+} from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
// import Chat from "./Chat";
// import React from "react";
import ChatContainerComponent from './ChatContainerComponent';
@@ -9,17 +14,17 @@ import socket from '../../../socket';
const ChatMenu = ({ selectedUser }) => {
function removeHiddenClass() {
- const element = document.querySelector('.chat-info');
+ const element = document.querySelector(".chat-info");
if (element) {
- element.classList.remove('hidden');
- document.querySelector('.chat-menu').style.width = '82%';
+ element.classList.remove("hidden");
+ document.querySelector(".chat-menu").style.width = "82%";
}
}
function addHiddenClass() {
- const element = document.querySelector('.chat-info');
+ const element = document.querySelector(".chat-info");
if (element) {
- element.classList.add('hidden');
- document.querySelector('.chat-menu').style.width = '100%';
+ element.classList.add("hidden");
+ document.querySelector(".chat-menu").style.width = "100%";
}
}
return (
diff --git a/client/src/pages/Home/SearchComponents/search.scss b/client/src/pages/Home/SearchComponents/search.scss
new file mode 100644
index 0000000..7cf9217
--- /dev/null
+++ b/client/src/pages/Home/SearchComponents/search.scss
@@ -0,0 +1,35 @@
+.hide-modal {
+ @apply absolute z-40 w-screen h-screen top-0 left-0 opacity-25
+ bg-slate-950;
+}
+
+#user-profile {
+ @apply bg-[#d9d9d9] w-[30rem] h-[30rem] absolute ml-[17rem]
+ translate-y-[-8rem] px-[2rem] py-[1rem] z-50;
+
+ .user-profile-upper {
+ @apply flex w-full;
+
+ .user-profile-upper-left {
+ @apply w-[50%] flex justify-between;
+ }
+
+ .user-profile-upper-right {
+ @apply w-[50%] flex justify-end items-center mr-[5%];
+ }
+
+ .user-profile-pic {
+ @apply h-[6rem] w-[6rem];
+ border-radius: 3rem;
+ }
+ }
+
+ .user-profile-description {
+ @apply bg-[#d28080] mt-[1rem] pl-[0.5rem] h-[60%];
+ }
+
+ .fat-btn {
+ @apply bg-[#d28080] flex justify-center items-center w-[120%] px-[0.2rem];
+ border-radius: 1rem;
+ }
+}
diff --git a/client/src/pages/Home/SearchComponents/searchedProfile.jsx b/client/src/pages/Home/SearchComponents/searchedProfile.jsx
index 7ef8c9b..8bceca7 100644
--- a/client/src/pages/Home/SearchComponents/searchedProfile.jsx
+++ b/client/src/pages/Home/SearchComponents/searchedProfile.jsx
@@ -1,14 +1,15 @@
-import UserProfile from './userProfile';
-import { useState, useEffect } from 'react';
-import { useContext } from 'react';
-import UserContext from '../../../Contexts/userContext';
-import PropTypes from 'prop-types';
+import UserProfile from "./userProfile";
+import { useState, useEffect } from "react";
+import { useContext } from "react";
+import UserContext from "../../../Contexts/userContext";
+import PropTypes from "prop-types";
const SearchedProfile = (props) => {
const [showConnectionProfile, setShowConnectionProfile] = useState(false);
const [showStrangerProfile, setShowStrangerProfile] = useState(false);
- const [SelectedUserProfileShowKey, setSelectedUserProfileShowKey] = useState(null);
- const [connectionStatus, setConnectionStatus] = useState(''); // New state variable
+ const [SelectedUserProfileShowKey, setSelectedUserProfileShowKey] =
+ useState(null);
+ const [connectionStatus, setConnectionStatus] = useState(""); // New state variable
const [dummyState, setDummyState] = useState(0); // Dummy state variable
const user = useContext(UserContext);
@@ -17,27 +18,29 @@ const SearchedProfile = (props) => {
// Pass the chatKey to handleShowProfile
setSelectedUserProfileShowKey(chatKey);
- if (section === 'connection') {
+ if (section === "connection") {
setShowConnectionProfile(!showConnectionProfile);
setShowStrangerProfile(false);
- } else if (section === 'stranger') {
+ } else if (section === "stranger") {
setShowStrangerProfile(!showStrangerProfile);
setShowConnectionProfile(false);
}
};
const [strangersSearchedResult, setStrangersSearchedResult] = useState([]);
- const [connectionsSearchedResult, setConnectionsSearchedResult] = useState([]);
+ const [connectionsSearchedResult, setConnectionsSearchedResult] = useState(
+ [],
+ );
useEffect(() => {
fetchData();
}, []); // Reload the component when connection status changes
const fetchData = async () => {
- const response = await fetch('http://localhost:3000/connection/search', {
- method: 'POST',
+ const response = await fetch("http://localhost:3000/connection/search", {
+ method: "POST",
headers: {
- 'Content-Type': 'application/json',
+ "Content-Type": "application/json",
},
body: JSON.stringify({
id: user._id,
@@ -52,7 +55,7 @@ const SearchedProfile = (props) => {
function truncateText(text, maxLength) {
if (text.length > maxLength) {
- return text.substring(0, maxLength) + '...';
+ return text.substring(0, maxLength) + "...";
}
return text;
}
@@ -62,14 +65,18 @@ const SearchedProfile = (props) => {
for (let i = 0; i < strangersSearchedResult.length; i++) {
const stranger = strangersSearchedResult[i];
- const truncatedDisplayName = truncateText(stranger.displayName, 18) || '';
- const pictureUrl = 'https://example.com/random-image.png';
+ const truncatedDisplayName = truncateText(stranger.displayName, 18) || "";
+ const pictureUrl = "https://example.com/random-image.png";
const chatKey = `stranger_${stranger._id}`;
renderedChats.push(
-
handleShowProfile(chatKey, 'stranger')}>
+
handleShowProfile(chatKey, "stranger")}
+ >
{truncatedDisplayName}
@@ -88,10 +95,11 @@ const SearchedProfile = (props) => {
description="Hardcoded description"
setConnectionStatus={setConnectionStatus}
setDummyState={setDummyState}
+ setShowProfile={setShowStrangerProfile}
/>
)}
-
+
,
);
}
@@ -105,36 +113,43 @@ const SearchedProfile = (props) => {
const connection = connectionsSearchedResult[i].userData;
if (!connection) continue;
- const truncatedDisplayName = truncateText(connection.displayName, 18) || '';
- const pictureUrl = 'https://example.com/random-image.png';
+ const truncatedDisplayName =
+ truncateText(connection.displayName, 18) || "";
+ const pictureUrl = "https://example.com/random-image.png";
const chatKey = `connection_${connection._id}`;
renderedChats.push(
-
handleShowProfile(chatKey, 'connection')}>
+
handleShowProfile(chatKey, "connection")}
+ >
{truncatedDisplayName}
@{connection.username}
- {showConnectionProfile && SelectedUserProfileShowKey === chatKey && (
-
- )}
+ {showConnectionProfile &&
+ SelectedUserProfileShowKey === chatKey && (
+
+ )}
-
+
,
);
}
@@ -142,9 +157,9 @@ const SearchedProfile = (props) => {
};
function removeHiddenChatMenu() {
- const element = document.querySelector < HTMLElement > '.chat-menu';
+ const element = document.querySelector < HTMLElement > ".chat-menu";
if (element) {
- element.classList.remove('hidden');
+ element.classList.remove("hidden");
}
}
diff --git a/client/src/pages/Home/SearchComponents/userProfile.jsx b/client/src/pages/Home/SearchComponents/userProfile.jsx
index ec85e7c..1fa17aa 100644
--- a/client/src/pages/Home/SearchComponents/userProfile.jsx
+++ b/client/src/pages/Home/SearchComponents/userProfile.jsx
@@ -1,5 +1,5 @@
-import FatButtons from '../../../SmallComponents/FatButtons';
-import PropTypes from 'prop-types';
+import FatButtons from "../../../SmallComponents/FatButtons";
+import PropTypes from "prop-types";
const UserProfile = (props) => {
const connectButtonText = (
@@ -20,10 +20,24 @@ const UserProfile = (props) => {
-

+
-
+
{props.displayName}
@@ -33,6 +47,12 @@ const UserProfile = (props) => {
{props.description}
+
{
+ props.setShowProfile(false);
+ }}
+ >
>
);
};
diff --git a/client/src/pages/pages-styles.scss b/client/src/pages/Home/home.scss
similarity index 59%
rename from client/src/pages/pages-styles.scss
rename to client/src/pages/Home/home.scss
index 1e73f84..52c93e1 100644
--- a/client/src/pages/pages-styles.scss
+++ b/client/src/pages/Home/home.scss
@@ -1,50 +1,5 @@
-@import '../index.scss';
-
-#Auth-Page {
- @apply w-screen h-screen text-center p-5
- flex flex-col justify-between items-center;
-
- > main {
- #Auth {
- @apply w-screen;
- .row {
- @apply w-full flex justify-between p-10;
-
- .Local-Auths,
- .Provided-Auths {
- @apply flex flex-col w-[600px] gap-5 justify-center items-center p-10
- text-xl;
-
- button {
- @apply w-full flex gap-5 justify-center;
- }
- }
- }
- }
-
- #Auth-Local {
- #Local-Backward {
- @apply absolute hover:scale-90;
- }
-
- #Local {
- @apply w-[400px]
- flex flex-col justify-center items-center gap-5;
-
- > #Submit-Button {
- @apply flex justify-between text-xl;
-
- > svg > path {
- fill: black;
- }
- }
- }
- }
- }
-}
-.hidden {
- display: none;
-}
+@import "../../index.scss";
+@import "./SearchComponents/search.scss";
#Home {
@apply bg-white w-[100vw] h-[100vh] flex flex-row;
@@ -179,75 +134,3 @@
}
}
}
-#user-profile {
- background-color: #d9d9d9;
- width: 30rem;
- height: 30rem;
- position: absolute;
- margin-left: 17rem;
- transform: translateY(-8rem);
- padding-left: 2rem;
- padding-right: 2rem;
- padding-top: 1rem;
- padding-bottom: 1rem;
-}
-
-.user-profile-upper {
- display: flex;
- flex-direction: row;
- width: 100%;
-
- .user-profile-upper-left {
- width: 50%;
- display: flex;
- justify-content: space-between;
- }
- .user-profile-upper-right {
- width: 50%;
- display: flex;
- justify-content: flex-end;
- align-items: center;
- margin-right: 5%;
- }
-
- .user-profile-pic {
- height: 6rem;
- width: 6rem;
- border-radius: 3rem;
- }
-}
-
-.user-profile-description {
- background-color: #d28080;
- margin-top: 1rem;
- padding-left: 0.5rem;
- height: 60%;
-}
-
-.fat-btn {
- background-color: #d28080;
- display: flex;
- justify-content: center;
- align-items: center;
- width: 120%;
- padding-left: 0.2rem;
- padding-right: 0.2rem;
- border-radius: 1rem;
-}
-
-@media screen and (max-width: 600px) {
- #Login-Page {
- > header > h3 {
- @apply text-3xl;
- }
-
- #Auth-Local {
- @apply p-5 justify-center;
- width: 100vw !important;
-
- #Local-Backward {
- left: 5vw;
- }
- }
- }
-}
diff --git a/client/src/pages/Home/index.jsx b/client/src/pages/Home/index.jsx
index 3d50ea2..b327ada 100644
--- a/client/src/pages/Home/index.jsx
+++ b/client/src/pages/Home/index.jsx
@@ -1,7 +1,7 @@
-import LeftBar from './LeftBar';
-import '../pages-styles.scss';
-import MessageMenu from './MessageMenu';
-import { IsSearchingProvider } from '../../Contexts/IsSearchingContext';
+import LeftBar from "./LeftBar";
+import "./home.scss";
+import MessageMenu from "./MessageMenu";
+import { IsSearchingProvider } from "../../Contexts/IsSearchingContext";
const index = () => {
return (
diff --git a/client/src/pages/Home/normalChats.jsx b/client/src/pages/Home/normalChats.jsx
index f31056e..41307bf 100644
--- a/client/src/pages/Home/normalChats.jsx
+++ b/client/src/pages/Home/normalChats.jsx
@@ -1,8 +1,8 @@
-import { useContext, useState, useEffect } from 'react';
-import UserContext from '../../Contexts/userContext';
+import { useContext, useState, useEffect } from "react";
+import UserContext from "../../Contexts/userContext";
-import PropTypes from 'prop-types';
-import socket from '../../socket';
+import PropTypes from "prop-types";
+import socket from "../../socket";
const NormalChats = ({ setSelectedUser }) => {
// State to store the chat connections
@@ -18,27 +18,27 @@ const NormalChats = ({ setSelectedUser }) => {
// Listen for connection errors and handle them
useEffect(() => {
- socket.on('connect_error', (err) => {
- if (err.message === 'User Does Not Exist') {
+ socket.on("connect_error", (err) => {
+ if (err.message === "User Does Not Exist") {
console.log(err);
}
});
// Remove the event listener on component unmount
- return () => socket.off('connect_error');
+ return () => socket.off("connect_error");
}, []);
// Function to fetch the user's chat connections from the server
const searchConnections = async function () {
- const response = await fetch('http://localhost:3000/connection/searchConnections', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- id: user._id,
- }),
- });
+ const response = await fetch(
+ "http://localhost:3000/connection/searchConnections",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
const data = await response.json();
setConnectionsArr(data);
};
@@ -46,7 +46,7 @@ const NormalChats = ({ setSelectedUser }) => {
// Function to truncate text if it exceeds a certain length
function truncateText(text, maxLength) {
if (text.length > maxLength) {
- return text.substring(0, maxLength) + '...';
+ return text.substring(0, maxLength) + "...";
}
return text;
}
@@ -64,9 +64,9 @@ const NormalChats = ({ setSelectedUser }) => {
// Function to remove the 'hidden' class from a chat menu (not shown in this snippet)
function removeHiddenChatMenu() {
- const element = document.querySelector('.chat-menu');
+ const element = document.querySelector(".chat-menu");
if (element) {
- element.classList.remove('hidden');
+ element.classList.remove("hidden");
}
}
@@ -101,13 +101,21 @@ const NormalChats = ({ setSelectedUser }) => {
{
- handleClick({ clickedOnUser: tmpArr[i], connection: connectionsArr[i] });
+ handleClick({
+ clickedOnUser: tmpArr[i],
+ connection: connectionsArr[i],
+ });
}}
key={i}
>
-

+
-
{truncateText(tmpArr[i].displayName, 18)}
+
+ {truncateText(tmpArr[i].displayName, 18)}
+
default text
diff --git a/client/vite.config.js b/client/vite.config.js
index 5a33944..9cc50ea 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -1,7 +1,7 @@
-import { defineConfig } from 'vite'
-import react from '@vitejs/plugin-react'
+import { defineConfig } from "vite";
+import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
-})
+});
diff --git a/server/config/passport.js b/server/config/passport.js
index d57b6e4..6c7b6b5 100644
--- a/server/config/passport.js
+++ b/server/config/passport.js
@@ -1,7 +1,7 @@
-const passport = require('passport');
-const LocalStrategy = require('passport-local').Strategy;
-const GoogleStrategy = require('passport-google-oidc');
-const User = require('../models/userModel');
+const passport = require("passport");
+const LocalStrategy = require("passport-local").Strategy;
+const GoogleStrategy = require("passport-google-oidc");
+const User = require("../models/userModel");
// Configure Passport
/**
@@ -14,10 +14,11 @@ passport.use(new LocalStrategy(User.authenticate()));
passport.use(
new GoogleStrategy(
{
- clientID: '441670067708-535huo2c4b5l3u05ntqf59dlsqteipm9.apps.googleusercontent.com',
- clientSecret: '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',
- callbackURL: '/oauth2/redirect/google',
- scope: ['profile', 'email'],
+ clientID:
+ "441670067708-535huo2c4b5l3u05ntqf59dlsqteipm9.apps.googleusercontent.com",
+ clientSecret: "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",
+ callbackURL: "/oauth2/redirect/google",
+ scope: ["profile", "email"],
},
async function verify(issuer, profile, cb) {
const param = await User.findOne({ googleId: profile.id });
@@ -34,8 +35,8 @@ passport.use(
} else {
return cb(null, param);
}
- }
- )
+ },
+ ),
);
passport.serializeUser(function (user, cb) {
diff --git a/server/controllers/connectionCRUD.js b/server/controllers/connectionCRUD.js
index 2ce90b3..a220b86 100644
--- a/server/controllers/connectionCRUD.js
+++ b/server/controllers/connectionCRUD.js
@@ -1,5 +1,5 @@
// Collection CRUD here
-const Connection = require('../models/connectionModel.js');
+const Connection = require("../models/connectionModel.js");
exports.createConnection = async function createConnection(_id, _id2) {
try {
@@ -26,7 +26,7 @@ exports.deleteConnection = async function deleteConnection(userOne, userTwo) {
}).exec();
if (!deletedConnection) {
- throw new Error('Connection not found');
+ throw new Error("Connection not found");
}
return deletedConnection;
diff --git a/server/controllers/userCRUD.js b/server/controllers/userCRUD.js
index 5ca6971..54073cb 100644
--- a/server/controllers/userCRUD.js
+++ b/server/controllers/userCRUD.js
@@ -1,5 +1,5 @@
-const User = require('../models/userModel.js');
-const Connection = require('../models/connectionModel.js');
+const User = require("../models/userModel.js");
+const Connection = require("../models/connectionModel.js");
/**
* Creates a new user in the database.
*
@@ -16,7 +16,7 @@ exports.createUser = async function createUser(userDetails) {
user = newUser;
return user;
} catch (error) {
- throw new Error('Failed to create user');
+ throw new Error("Failed to create user");
}
};
@@ -37,7 +37,7 @@ exports.findUser = async function findUser(reference) {
return user;
}
} catch (error) {
- throw new Error('Failed to get user', error);
+ throw new Error("Failed to get user", error);
}
};
@@ -57,12 +57,12 @@ exports.updateUser = async function updateUser(_id, updateKeys) {
new: true,
});
if (!updatedUser) {
- throw new Error('User not found');
+ throw new Error("User not found");
}
user = updatedUser;
return user;
} catch (error) {
- throw new Error('Failed to update user');
+ throw new Error("Failed to update user");
}
};
@@ -80,11 +80,11 @@ exports.deleteUser = async function deleteUser(_id) {
try {
await User.findByIdAndDelete(_id);
- if (!deleteUser) throw new Error('User not found');
+ if (!deleteUser) throw new Error("User not found");
deleteSuccessful = true;
return user;
} catch (error) {
- throw new Error('Failed to delete user');
+ throw new Error("Failed to delete user");
}
};
@@ -101,18 +101,27 @@ exports.searchUsers = async function searchUsers(id, searchTerm) {
});
// Find strangers with display names matching the search term
- const strangers = await User.find({ displayName: { $regex: `^${searchTerm}`, $options: 'i' } });
+ const strangers = await User.find({
+ displayName: { $regex: `^${searchTerm}`, $options: "i" },
+ });
// Remove the objects from strangers that have matching IDs with connections
const updatedStrangers = strangers.filter((stranger) => {
return !connections.some((connection) => {
- return connection.userOne.toString() === stranger._id.toString() || connection.userTwo.toString() === stranger._id.toString();
+ return (
+ connection.userOne.toString() === stranger._id.toString() ||
+ connection.userTwo.toString() === stranger._id.toString()
+ );
});
});
// Fetch additional user data for connections
const connectionDataPromises = connections.map(async (connection) => {
- const otherUserId = (connection.userOne.toString() === id ? connection.userTwo : connection.userOne).toString();
+ const otherUserId = (
+ connection.userOne.toString() === id
+ ? connection.userTwo
+ : connection.userOne
+ ).toString();
const userData = await User.findById(otherUserId);
return {
userData,
@@ -125,7 +134,10 @@ exports.searchUsers = async function searchUsers(id, searchTerm) {
userData,
}));
// Filter connectionsWithUserData based on the search term
- const filteredConnectionUserData = connectionsWithUserData.filter(({ userData }) => userData.displayName.toLowerCase().includes(searchTerm.toLowerCase()));
+ const filteredConnectionUserData = connectionsWithUserData.filter(
+ ({ userData }) =>
+ userData.displayName.toLowerCase().includes(searchTerm.toLowerCase()),
+ );
return [filteredConnectionUserData, updatedStrangers];
};
diff --git a/server/index.js b/server/index.js
index 307eaff..f3aec16 100644
--- a/server/index.js
+++ b/server/index.js
@@ -1,34 +1,34 @@
-const express = require('express');
-const cors = require('cors');
-const session = require('express-session');
-const MongoDBStore = require('connect-mongo')(session);
-require('dotenv').config();
-
-const { mongoDB_url, port } = require('./store.js');
-const connectDatabase = require('./database/mongodb.js');
-const passport = require('./config/passport.js');
-
-const userRoutes = require('./routes/userRoutes.js');
-const connectionRoutes = require('./routes/connectionRoutes.js');
-const authRoutes = require('./routes/authRoutes.js');
-const messageRoutes = require('./routes/messageRoutes.js');
-const googleRoutes = require('./routes/googleAuth.js');
+const express = require("express");
+const cors = require("cors");
+const session = require("express-session");
+const MongoDBStore = require("connect-mongo")(session);
+require("dotenv").config();
+
+const { mongoDB_url, port } = require("./store.js");
+const connectDatabase = require("./database/mongodb.js");
+const passport = require("./config/passport.js");
+
+const userRoutes = require("./routes/userRoutes.js");
+const connectionRoutes = require("./routes/connectionRoutes.js");
+const authRoutes = require("./routes/authRoutes.js");
+const messageRoutes = require("./routes/messageRoutes.js");
+const googleRoutes = require("./routes/googleAuth.js");
// Connect to the MongoDB database
connectDatabase();
// Create an instance of the Express application
const app = express();
-const httpServer = require('http').createServer(app);
-const io = require('socket.io')(httpServer, {
+const httpServer = require("http").createServer(app);
+const io = require("socket.io")(httpServer, {
cors: {
- origin: 'http://localhost:8000',
+ origin: "http://localhost:8000",
},
});
// Configure Cross-Origin Resource Sharing (CORS) options
const corsOptions = {
- origin: 'http://localhost:8000', // Allow requests from this origin
+ origin: "http://localhost:8000", // Allow requests from this origin
credentials: true, // Enable sending cookies in cross-origin requests
};
@@ -75,21 +75,25 @@ app.use(passport.initialize());
app.use(passport.session());
// Endpoint to handle HTTP GET request to '/home'
-app.get('http://localhost:8000/home', passport.authenticate('local'), (req, res) => {});
+app.get(
+ "http://localhost:8000/home",
+ passport.authenticate("local"),
+ (req, res) => {}
+);
// Route handlers for user-related functionality
-app.use('/user', userRoutes);
+app.use("/user", userRoutes);
// Route handlers for authentication-related functionality
-app.use('/auth', authRoutes);
+app.use("/auth", authRoutes);
// Route handlers for connection-related functionality
-app.use('/connection', connectionRoutes);
+app.use("/connection", connectionRoutes);
// Route handlers for message-related functionality
-app.use('/message', messageRoutes);
+app.use("/message", messageRoutes);
// Route handlers for google authentication related functionality
-app.use('/', googleRoutes);
+app.use("/", googleRoutes);
// Socket.IO middleware function for authentication and authorization.
io.use((socket, next) => {
@@ -99,7 +103,7 @@ io.use((socket, next) => {
// Check if the 'clickedOnUser' flag exists in the authentication data.
if (!clickedOnUser) {
// If the flag is missing, send an error to the client and abort the connection.
- return next(new Error('User Does Not Exist'));
+ return next(new Error("User Does Not Exist"));
}
// If the user is authenticated, attach the 'connection' data to the socket for later use.
@@ -108,7 +112,7 @@ io.use((socket, next) => {
});
// Event listener for a new socket connection.
-io.on('connection', (socket) => {
+io.on("connection", (socket) => {
// Log the ID of the connected socket.
console.log(socket.id);
@@ -116,15 +120,15 @@ io.on('connection', (socket) => {
socket.join(socket.connection._id);
// Event listener for 'private_message' events from the client.
- socket.on('private_message', async (data) => {
+ socket.on("private_message", async (data) => {
// Emit the 'new_message' event to all sockets in the same room.
- io.to(socket.connection._id).emit('new_message', data);
+ io.to(socket.connection._id).emit("new_message", data);
});
// Event listener for 'disconnect' events from the client.
- socket.on('disconnect', () => {
+ socket.on("disconnect", () => {
// Log a message when a user disconnects.
- console.log('User has disconnected');
+ console.log("User has disconnected");
});
});
// Start the server and listen for incoming requests
diff --git a/server/models/connectionModel.js b/server/models/connectionModel.js
index b9d29c8..f95574e 100644
--- a/server/models/connectionModel.js
+++ b/server/models/connectionModel.js
@@ -1,4 +1,4 @@
-const mongoose = require('mongoose');
+const mongoose = require("mongoose");
// Create a new Mongoose schema
const Schema = mongoose.Schema;
@@ -7,13 +7,13 @@ const Schema = mongoose.Schema;
const connectionSchema = new Schema({
userOne: {
type: mongoose.Schema.Types.ObjectId,
- ref: 'User',
+ ref: "User",
},
userTwo: {
type: mongoose.Schema.Types.ObjectId,
- ref: 'User',
+ ref: "User",
},
});
// Create and export the Connection model based on the connection schema
-module.exports = mongoose.model('Connection', connectionSchema);
+module.exports = mongoose.model("Connection", connectionSchema);
diff --git a/server/models/userModel.js b/server/models/userModel.js
index de9d840..8bffe0a 100644
--- a/server/models/userModel.js
+++ b/server/models/userModel.js
@@ -1,5 +1,5 @@
-const mongoose = require('mongoose');
-const passportLocalMongoose = require('passport-local-mongoose');
+const mongoose = require("mongoose");
+const passportLocalMongoose = require("passport-local-mongoose");
// Create a new Mongoose schema
const Schema = mongoose.Schema;
@@ -10,12 +10,12 @@ const userSchema = new Schema({
email: { type: String, required: true, unique: true }, // User's email field
displayName: { type: String, sparse: true },
googleId: { type: String, required: false, unique: true },
- provider: { type: String, required: false }
+ provider: { type: String, required: false },
// imageUrl: String, // Uncomment this line to include an imageUrl field
});
// Plugin passport-local-mongoose to the user schema
-userSchema.plugin(passportLocalMongoose, { usernameQueryFields: ['email'] });
+userSchema.plugin(passportLocalMongoose, { usernameQueryFields: ["email"] });
// Create and export the User model based on the user schema
-module.exports = mongoose.model('User', userSchema);
+module.exports = mongoose.model("User", userSchema);
diff --git a/server/routes/authRoutes.js b/server/routes/authRoutes.js
index a4e4087..baeca43 100644
--- a/server/routes/authRoutes.js
+++ b/server/routes/authRoutes.js
@@ -1,18 +1,18 @@
-const express = require('express');
-const passport = require('passport');
-const User = require('../models/userModel');
+const express = require("express");
+const passport = require("passport");
+const User = require("../models/userModel");
// Create a new Router instance
const authRouter = express.Router();
// Endpoint to handle user login
-authRouter.post('/login', passport.authenticate('local'), (req, res) => {
+authRouter.post("/login", passport.authenticate("local"), (req, res) => {
// Log the request body
- res.send('logged in');
+ res.send("logged in");
});
// Endpoint to handle user registration
-authRouter.post('/register', (req, res) => {
+authRouter.post("/register", (req, res) => {
const { email, username, password } = req.body;
const newUser = new User({ username, email });
@@ -22,9 +22,9 @@ authRouter.post('/register', (req, res) => {
if (err) {
} else {
// Authenticate the user after successful registration
- passport.authenticate('local')(req, res, () => {
+ passport.authenticate("local")(req, res, () => {
// console.log(req.user);
- res.send('registered and logged in');
+ res.send("registered and logged in");
});
}
});
@@ -35,7 +35,7 @@ authRouter.post('/register', (req, res) => {
* @param {Object} req - Express request object
* @param {Object} res - Express response object
*/
-authRouter.get('/check', (req, res) => {
+authRouter.get("/check", (req, res) => {
let user;
// Check if the user is authenticated
if (req.user) {
@@ -54,11 +54,11 @@ authRouter.get('/check', (req, res) => {
});
// Endpoint to handle user logout
-authRouter.get('/logout', (req, res) => {
+authRouter.get("/logout", (req, res) => {
// Logout the user and clear the session
req.logout(req.user, (err) => {
if (err) return next(err);
- res.redirect('/');
+ res.redirect("/");
});
});
diff --git a/server/routes/connectionRoutes.js b/server/routes/connectionRoutes.js
index 84e0177..25fdb23 100644
--- a/server/routes/connectionRoutes.js
+++ b/server/routes/connectionRoutes.js
@@ -1,7 +1,11 @@
-const { Router } = require('express');
-const { createConnection, findUserConnections, deleteConnection } = require('../controllers/connectionCRUD.js');
-const { searchUsers } = require('../controllers/userCRUD.js');
-const { defaultResponse } = require('../store.js');
+const { Router } = require("express");
+const {
+ createConnection,
+ findUserConnections,
+ deleteConnection,
+} = require("../controllers/connectionCRUD.js");
+const { searchUsers } = require("../controllers/userCRUD.js");
+const { defaultResponse } = require("../store.js");
// Create a new Router instance
const connectionRoutes = Router();
@@ -10,7 +14,7 @@ const connectionRoutes = Router();
// Creating a New Connection
-connectionRoutes.post('/', async (req, res) => {
+connectionRoutes.post("/", async (req, res) => {
// Endpoint to create new connection
// Params: userOne id
// Body: userTwo id
@@ -23,19 +27,23 @@ connectionRoutes.post('/', async (req, res) => {
let connectionAlreadyExists = false;
connections.forEach((connection) => {
- if ((connection.userOne._id === _id && connection.userTwo.id === _id2) || (connection.userOne._id === _id2 && connection.userTwo._id === _id)) connectionAlreadyExists = true;
+ if (
+ (connection.userOne._id === _id && connection.userTwo.id === _id2) ||
+ (connection.userOne._id === _id2 && connection.userTwo._id === _id)
+ )
+ connectionAlreadyExists = true;
});
if (connectionAlreadyExists) {
- response.log = 'connection already exists';
+ response.log = "connection already exists";
} else {
const newConnection = await createConnection(_id, _id2);
if (!newConnection) {
- response.log = 'failed to create new connection';
+ response.log = "failed to create new connection";
} else {
response.success = true;
- response.log = 'new connection created';
+ response.log = "new connection created";
response.data = { newConnection };
}
}
@@ -45,7 +53,7 @@ connectionRoutes.post('/', async (req, res) => {
// Searching for Connections and Strangers
-connectionRoutes.post('/search', async (req, res) => {
+connectionRoutes.post("/search", async (req, res) => {
// Endpoint to search for connections and strangers
// Params: id, searchTerm
// Response: Connections and strangers based on the search term
@@ -62,7 +70,7 @@ connectionRoutes.post('/search', async (req, res) => {
res.json(data);
});
-connectionRoutes.post('/searchConnections', async (req, res) => {
+connectionRoutes.post("/searchConnections", async (req, res) => {
// Endpoint to search for connections and strangers
// Params: id, searchTerm
// Response: Connections and strangers based on the search term
@@ -101,15 +109,15 @@ connectionRoutes.post('/searchConnections', async (req, res) => {
// res.json(response);
// });
-connectionRoutes.delete('/:userOne/:userTwo', async (req, res) => {
+connectionRoutes.delete("/:userOne/:userTwo", async (req, res) => {
const { userOne, userTwo } = req.params;
try {
const result = await deleteConnection(userOne, userTwo);
console.log(result);
- res.status(200).json({ message: 'Connection deleted successfully' });
+ res.status(200).json({ message: "Connection deleted successfully" });
} catch (error) {
- res.status(500).json({ error: 'Failed to delete connection' });
+ res.status(500).json({ error: "Failed to delete connection" });
}
});
diff --git a/server/routes/googleAuth.js b/server/routes/googleAuth.js
index ffa4218..7f059e6 100644
--- a/server/routes/googleAuth.js
+++ b/server/routes/googleAuth.js
@@ -1,12 +1,15 @@
-const passport = require('passport');
-const express = require('express');
+const passport = require("passport");
+const express = require("express");
const googleRouter = express.Router();
-googleRouter.get('/login/federated/google', passport.authenticate('google'));
+googleRouter.get("/login/federated/google", passport.authenticate("google"));
-googleRouter.get('/oauth2/redirect/google', passport.authenticate('google', {
- successRedirect: 'http://localhost:8000/home',
- failureRedirect: 'http://localhost:8000/'
-}));
+googleRouter.get(
+ "/oauth2/redirect/google",
+ passport.authenticate("google", {
+ successRedirect: "http://localhost:8000/home",
+ failureRedirect: "http://localhost:8000/",
+ }),
+);
module.exports = googleRouter;
diff --git a/server/routes/userRoutes.js b/server/routes/userRoutes.js
index 80dc050..551d79e 100644
--- a/server/routes/userRoutes.js
+++ b/server/routes/userRoutes.js
@@ -1,13 +1,17 @@
-const { Router } = require('express');
-const { deleteUser, findUser, updateUser } = require('../controllers/userCRUD.js');
-const { defaultResponse } = require('../store.js');
+const { Router } = require("express");
+const {
+ deleteUser,
+ findUser,
+ updateUser,
+} = require("../controllers/userCRUD.js");
+const { defaultResponse } = require("../store.js");
// Create a new Router instance
const userRoutes = Router();
// RESTful API routes for user operations
-userRoutes.get('/:_id', async (req, res) => {
+userRoutes.get("/:_id", async (req, res) => {
// Endpoint to get user details based on the provided ID
// Params: _id - User ID
// Response: User details from the provided ID
@@ -17,17 +21,17 @@ userRoutes.get('/:_id', async (req, res) => {
const response = defaultResponse();
if (!user) {
- response.log = 'user not found';
+ response.log = "user not found";
} else {
response.success = true;
- response.log = 'user found';
+ response.log = "user found";
response.data = { user };
}
res.json(response);
});
-userRoutes.patch('/:_id', async (req, res) => {
+userRoutes.patch("/:_id", async (req, res) => {
// Endpoint to update user details based on the provided ID
// Params: _id - User ID
// Body: updateKeys - Updated user data
@@ -40,17 +44,17 @@ userRoutes.patch('/:_id', async (req, res) => {
const user = await updateUser(_id, updateKeys);
if (user) {
- response.log = 'user not found';
+ response.log = "user not found";
} else {
response.success = true;
- response.log = 'user updated';
+ response.log = "user updated";
response.data = { user };
}
res.json(response);
});
-userRoutes.delete('/:_id', async (req, res) => {
+userRoutes.delete("/:_id", async (req, res) => {
// Endpoint to delete a user based on the provided ID
// Params: _id - User ID
// Response: Deleted user
@@ -60,10 +64,10 @@ userRoutes.delete('/:_id', async (req, res) => {
const userDeleted = await deleteUser(_id);
if (!userDeleted) {
- response.log = 'failed to delete user';
+ response.log = "failed to delete user";
} else {
response.success = true;
- response.log = 'user deleted';
+ response.log = "user deleted";
response.data = { user: userDeleted };
}
diff --git a/server/seeders/userSeed.js b/server/seeders/userSeed.js
index 7e76856..836b065 100644
--- a/server/seeders/userSeed.js
+++ b/server/seeders/userSeed.js
@@ -1,9 +1,15 @@
+<<<<<<< HEAD:server/userSeed.js
+const mongoose = require("mongoose");
+const { faker } = require("@faker-js/faker");
+const User = require("./models/userModel.js");
+=======
const mongoose = require('mongoose');
const { faker } = require('@faker-js/faker');
const User = require('../models/userModel.js');
+>>>>>>> main:server/seeders/userSeed.js
// Connect to your MongoDB database
-mongoose.connect('mongodb://127.0.0.1/Synapse', {
+mongoose.connect("mongodb://127.0.0.1/Synapse", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
@@ -13,13 +19,13 @@ const generatedUsername = new Set();
//Clears existing data and inserts new records into the User collection.
async function seed() {
try {
- console.log('Initializing data seeding...');
+ console.log("Initializing data seeding...");
const startTime = new Date().getTime();
// Clear the User collection
- console.log('Clearing the users collection...');
+ console.log("Clearing the users collection...");
await User.deleteMany({});
- console.log('The users collection has been cleared.');
+ console.log("The users collection has been cleared.");
const totalUsers = 10; // Change this value to the desired number of total users
const batchSize = Math.ceil((totalUsers / 100) * 1); // Batch size as 1% of total users
@@ -66,14 +72,14 @@ async function seed() {
const insertTime = (userInsertEnd - userInsertStart) / 1000; // in seconds
- console.log('Seeding finished.');
+ console.log("Seeding finished.");
console.log(`Total Users: ${totalUsers}`);
console.log(`Data insertion time: ${insertTime.toFixed(2)} seconds`);
console.log(`Total Time Taken: ${totalTime.toFixed(2)} seconds`);
console.log(`Inserted Users: ${insertedUsers}`);
console.log(`Progress: 100%`);
} catch (error) {
- console.error('Error seeding data:', error.message);
+ console.error("Error seeding data:", error.message);
} finally {
mongoose.disconnect();
}
diff --git a/server/store.js b/server/store.js
index 47845f8..0cf438f 100644
--- a/server/store.js
+++ b/server/store.js
@@ -9,13 +9,15 @@ exports.port = port;
exports.url = `http://localhost:${port}`;
// MongoDB connection URL
-exports.mongoDB_url = 'mongodb://127.0.0.1/Synapse';
+exports.mongoDB_url = "mongodb://127.0.0.1/Synapse";
+// exports.mongoDB_url = process.env.CLUSTER0;
+
// Default response structure
exports.defaultResponse = function () {
// Create a default response object
const response = {
success: false, // Indicates if the request was successful or not
- log: 'default response', // Log message for debugging or informational purposes
+ log: "default response", // Log message for debugging or informational purposes
data: undefined, // Data to be sent as a response (if any)
};
diff --git a/server/tests/index.test.js b/server/tests/index.test.js
index a3fa1b8..ba87b7e 100644
--- a/server/tests/index.test.js
+++ b/server/tests/index.test.js
@@ -17,7 +17,7 @@ describe("testing for index.ts", () => {
// gets text from html file
const htmlText = fs.readFileSync(
path.join(__dirname, "../index.html"),
- "utf8"
+ "utf8",
);
// since our root route serves a html file
diff --git a/server/tests/user.test.js b/server/tests/user.test.js
index c40bdd0..e3762dc 100644
--- a/server/tests/user.test.js
+++ b/server/tests/user.test.js
@@ -27,7 +27,7 @@ describe("perform CRUD on user", () => {
it("authenticates user using email and passowrd", async () => {
const response = await authenticateUser(
userDetails.email,
- userDetails.password
+ userDetails.password,
);
expect(response.log).toBe("user authenticated");
@@ -38,7 +38,7 @@ describe("perform CRUD on user", () => {
it("tries to authenticates user using wrong email but right passowrd", async () => {
const response = await authenticateUser(
userDetails.email + "xxx",
- userDetails.password
+ userDetails.password,
);
expect(response.log).toBe("user not found");
@@ -49,7 +49,7 @@ describe("perform CRUD on user", () => {
it("tries to authenticates user using right email but wrong passowrd", async () => {
const response = await authenticateUser(
userDetails.email,
- userDetails.password + "xxx"
+ userDetails.password + "xxx",
);
expect(response.log).toBe("wrong password or username");
@@ -60,7 +60,7 @@ describe("perform CRUD on user", () => {
it("tries to authenticates user using wrong email and passowrd", async () => {
const response = await authenticateUser(
userDetails.email + "xxx",
- userDetails.password + "xxx"
+ userDetails.password + "xxx",
);
expect(response.log).toBe("user not found");