From e964332795b9403d93d82069b1cb180d051f737c Mon Sep 17 00:00:00 2001 From: Aditya81016 Date: Thu, 3 Aug 2023 15:02:11 +0530 Subject: [PATCH] minor changes --- .gitignore | 2 + client/.eslintrc.cjs | 18 +-- client/index.html | 7 +- client/postcss.config.js | 2 +- client/src/App.jsx | 28 ++-- client/src/Contexts/IsSearchingContext.jsx | 10 +- client/src/Contexts/userContext.js | 2 +- client/src/SmallComponents/FatButtons.jsx | 40 +++--- client/src/main.jsx | 2 +- client/src/pages/Auth/Auth.jsx | 66 +++++++--- client/src/pages/Auth/Local.jsx | 105 +++++++++------ client/src/pages/Auth/auth.scss | 61 +++++++++ client/src/pages/Auth/index.jsx | 2 +- client/src/pages/Home/DirectAccess.jsx | 37 ++++-- client/src/pages/Home/LeftBar.jsx | 21 ++- .../ChatContainerComponent.jsx | 31 +++-- .../MessageComponents/ChatInfoButtons.jsx | 55 ++++---- .../pages/Home/MessageComponents/ChatMenu.jsx | 79 +++++++----- client/src/pages/Home/MessageMenu.jsx | 4 +- .../pages/Home/SearchComponents/search.scss | 35 +++++ .../Home/SearchComponents/searchedProfile.jsx | 91 +++++++------ .../Home/SearchComponents/userProfile.jsx | 28 +++- .../{pages-styles.scss => Home/home.scss} | 121 +----------------- client/src/pages/Home/index.jsx | 8 +- client/src/pages/Home/normalChats.jsx | 46 ++++--- client/vite.config.js | 6 +- server/config/passport.js | 21 +-- server/controllers/connectionCRUD.js | 4 +- server/controllers/userCRUD.js | 36 ++++-- server/index.js | 5 +- server/models/connectionModel.js | 8 +- server/models/userModel.js | 10 +- server/routes/authRoutes.js | 22 ++-- server/routes/connectionRoutes.js | 36 ++++-- server/routes/googleAuth.js | 17 ++- server/routes/userRoutes.js | 28 ++-- server/store.js | 6 +- server/tests/index.test.js | 2 +- server/tests/user.test.js | 8 +- server/userSeed.js | 18 +-- 40 files changed, 653 insertions(+), 475 deletions(-) create mode 100644 .gitignore create mode 100644 client/src/pages/Auth/auth.scss create mode 100644 client/src/pages/Home/SearchComponents/search.scss rename client/src/pages/{pages-styles.scss => Home/home.scss} (59%) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5f19d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +package-lock.json diff --git a/client/.eslintrc.cjs b/client/.eslintrc.cjs index ec601b2..d08f6de 100644 --- a/client/.eslintrc.cjs +++ b/client/.eslintrc.cjs @@ -1,15 +1,15 @@ module.exports = { env: { browser: true, es2020: true }, extends: [ - 'eslint:recommended', - 'plugin:react/recommended', - 'plugin:react/jsx-runtime', - 'plugin:react-hooks/recommended', + "eslint:recommended", + "plugin:react/recommended", + "plugin:react/jsx-runtime", + "plugin:react-hooks/recommended", ], - parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, - settings: { react: { version: '18.2' } }, - plugins: ['react-refresh'], + parserOptions: { ecmaVersion: "latest", sourceType: "module" }, + settings: { react: { version: "18.2" } }, + plugins: ["react-refresh"], rules: { - 'react-refresh/only-export-components': 'warn', + "react-refresh/only-export-components": "warn", }, -} +}; diff --git a/client/index.html b/client/index.html index e67e024..2cf2fa0 100644 --- a/client/index.html +++ b/client/index.html @@ -1,10 +1,13 @@ - + - + Synapse diff --git a/client/postcss.config.js b/client/postcss.config.js index 2e7af2b..2aa7205 100644 --- a/client/postcss.config.js +++ b/client/postcss.config.js @@ -3,4 +3,4 @@ export default { tailwindcss: {}, autoprefixer: {}, }, -} +}; diff --git a/client/src/App.jsx b/client/src/App.jsx index 53be66a..88295c8 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -1,9 +1,9 @@ -import { Route, BrowserRouter, Routes, Navigate } from 'react-router-dom'; -import AuthPage from './pages/Auth'; -import RootPage from './pages/Root'; -import Home from './pages/Home'; -import { useEffect, useState } from 'react'; -import UserContext from './Contexts/userContext'; +import { Route, BrowserRouter, Routes, Navigate } from "react-router-dom"; +import AuthPage from "./pages/Auth"; +import RootPage from "./pages/Root"; +import Home from "./pages/Home"; +import { useEffect, useState } from "react"; +import UserContext from "./Contexts/userContext"; function App() { const [authenticated, setAuthenticated] = useState(false); @@ -22,8 +22,8 @@ function App() { */ const checkAuth = async () => { try { - const response = await fetch('http://localhost:3000/auth/check', { - credentials: 'include', + const response = await fetch("http://localhost:3000/auth/check", { + credentials: "include", }); const data = await response.json(); setUser(data.user); @@ -37,7 +37,7 @@ function App() { // Render a loading state until authentication check is complete if (!authChecked) { - return
Loading...
; + return
Loading...
; } return ( @@ -46,8 +46,14 @@ function App() { } /> {/* Protected route: If authenticated, render the Home component. Otherwise, navigate to the Auth page */} - : } /> - } /> + : } + /> + } + /> diff --git a/client/src/Contexts/IsSearchingContext.jsx b/client/src/Contexts/IsSearchingContext.jsx index bf96e7e..86afdc1 100644 --- a/client/src/Contexts/IsSearchingContext.jsx +++ b/client/src/Contexts/IsSearchingContext.jsx @@ -1,12 +1,16 @@ -import { createContext, useState } from 'react'; -import PropTypes from 'prop-types'; +import { createContext, useState } from "react"; +import PropTypes from "prop-types"; const IsSearchingContext = createContext(); export const IsSearchingProvider = ({ children }) => { const [isSearching, setIsSearching] = useState(false); - return {children}; + return ( + + {children} + + ); }; IsSearchingProvider.propTypes = { children: PropTypes.node.isRequired, diff --git a/client/src/Contexts/userContext.js b/client/src/Contexts/userContext.js index 4f7497d..1fd39f5 100644 --- a/client/src/Contexts/userContext.js +++ b/client/src/Contexts/userContext.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from "react"; const UserContext = React.createContext(); diff --git a/client/src/SmallComponents/FatButtons.jsx b/client/src/SmallComponents/FatButtons.jsx index 3d85906..34c212c 100644 --- a/client/src/SmallComponents/FatButtons.jsx +++ b/client/src/SmallComponents/FatButtons.jsx @@ -1,6 +1,6 @@ -import PropTypes from 'prop-types'; -import { useContext } from 'react'; -import UserContext from '../Contexts/userContext'; +import PropTypes from "prop-types"; +import { useContext } from "react"; +import UserContext from "../Contexts/userContext"; const FatButtons = (props) => { const user = useContext(UserContext); @@ -10,10 +10,10 @@ const FatButtons = (props) => { const _id = user._id; // Replace with the userOne ID const _id2 = props._id2; // Replace with the userTwo ID - const response = await fetch('http://localhost:3000/connection', { - method: 'POST', + const response = await fetch("http://localhost:3000/connection", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify({ id: _id, @@ -22,17 +22,17 @@ const FatButtons = (props) => { }); if (response.ok) { - props.setConnectionStatus('connected'); // Update the connection status + props.setConnectionStatus("connected"); // Update the connection status props.setDummyState((prevState) => prevState + 1); // Increment the dummy state variable const data = await response.json(); // Handle the response data here console.log(data); } else { - throw new Error('Failed to create connection'); + throw new Error("Failed to create connection"); } } catch (error) { // Handle any errors that occur during the request - console.error('Error creating connection:', error); + console.error("Error creating connection:", error); } console.log(user); } @@ -42,29 +42,37 @@ const FatButtons = (props) => { const _id = user._id; // Replace with the userOne ID const _id2 = props._id2; // Replace with the userTwo ID - const response = await fetch(`http://localhost:3000/connection/${_id}/${_id2}`, { - method: 'DELETE', - }); + const response = await fetch( + `http://localhost:3000/connection/${_id}/${_id2}`, + { + method: "DELETE", + }, + ); if (response.ok) { const data = await response.json(); - props.setConnectionStatus('disconnected'); // Update the connection status + props.setConnectionStatus("disconnected"); // Update the connection status props.setDummyState((prevState) => prevState + 1); // Increment the dummy state variable // Handle the response data here console.log(data); // Perform any necessary actions after successful disconnection } else { - throw new Error('Failed to delete connection'); + throw new Error("Failed to delete connection"); } } catch (error) { // Handle any errors that occur during the request - console.error('Error deleting connection:', error); + console.error("Error deleting connection:", error); } } return (
-
diff --git a/client/src/main.jsx b/client/src/main.jsx index af80bdf..801f97f 100644 --- a/client/src/main.jsx +++ b/client/src/main.jsx @@ -6,5 +6,5 @@ import "./index.scss"; ReactDOM.createRoot(document.getElementById("root")).render( - + , ); diff --git a/client/src/pages/Auth/Auth.jsx b/client/src/pages/Auth/Auth.jsx index 66307e6..ab58fbb 100644 --- a/client/src/pages/Auth/Auth.jsx +++ b/client/src/pages/Auth/Auth.jsx @@ -1,49 +1,81 @@ -import { useState } from 'react'; -import Local from './Local'; -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { faFacebook, faGoogle, faTwitter } from '@fortawesome/free-brands-svg-icons'; -import PropTypes from 'prop-types'; +import { useState } from "react"; +import Local from "./Local"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { + faFacebook, + faGoogle, + faTwitter, +} from "@fortawesome/free-brands-svg-icons"; +import PropTypes from "prop-types"; export default function Auth({ setAuthenticated }) { - const [activePage, setActivePage] = useState(['Auth', '']); + const [activePage, setActivePage] = useState(["Auth", ""]); function fade_to_Local(passed_page) { - document.getElementById('Auth')?.classList.add('fade-out-r-l'); + document.getElementById("Auth")?.classList.add("fade-out-r-l"); setTimeout(() => { setActivePage(passed_page); - document.getElementById('Auth')?.classList.remove('fade-out-r-l'); + document.getElementById("Auth")?.classList.remove("fade-out-r-l"); }, 475 /*fade-out-r-l*/); } return ( <> -
- +
+
-
+
- -
- - - - diff --git a/client/src/pages/Auth/Local.jsx b/client/src/pages/Auth/Local.jsx index 3b31947..22d95f7 100644 --- a/client/src/pages/Auth/Local.jsx +++ b/client/src/pages/Auth/Local.jsx @@ -1,27 +1,27 @@ -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { faArrowLeft, faArrowRight } from '@fortawesome/free-solid-svg-icons'; -import InputGroup from '../../assets/InputGroup'; -import { useState } from 'react'; -import { useNavigate } from 'react-router-dom'; -import PropTypes from 'prop-types'; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { faArrowLeft, faArrowRight } from "@fortawesome/free-solid-svg-icons"; +import InputGroup from "../../assets/InputGroup"; +import { useState } from "react"; +import { useNavigate } from "react-router-dom"; +import PropTypes from "prop-types"; export default function Local({ setAuthenticated, setActivePage, method }) { - const [valueEmail, setValueEmail] = useState(''); // State variable for email input value - const [valuePassword, setValuePassword] = useState(''); // State variable for password input value - const [valueUsername, setValueUsername] = useState(''); // State variable for username input value + const [valueEmail, setValueEmail] = useState(""); // State variable for email input value + const [valuePassword, setValuePassword] = useState(""); // State variable for password input value + const [valueUsername, setValueUsername] = useState(""); // State variable for username input value const navigate = useNavigate(); // Function for programmatic navigation let formData; // Form data object - if (method === 'Login') { + if (method === "Login") { // Construct form data for login method - if (valueEmail === '') { + if (valueEmail === "") { formData = { username: valueUsername, password: valuePassword, }; - } else if (valueUsername === '') { + } else if (valueUsername === "") { formData = { username: valueEmail, password: valuePassword, @@ -39,54 +39,56 @@ export default function Local({ setAuthenticated, setActivePage, method }) { async function handleSubmit(event) { event.preventDefault(); - if (method === 'Login') { + if (method === "Login") { // Handle login form submission - const response = await fetch('http://localhost:3000/auth/login', { - method: 'POST', + const response = await fetch("http://localhost:3000/auth/login", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify(formData), - credentials: 'include', // Include cookies in the request + credentials: "include", // Include cookies in the request }); if (response.status === 200) { // Authentication successful setAuthenticated(true); setTimeout(() => { - navigate('/home'); // Redirect to /home after a small delay + navigate("/home"); // Redirect to /home after a small delay }, 500); } } else { // Handle register form submission - const response = await fetch('http://localhost:3000/auth/register', { - method: 'POST', + const response = await fetch("http://localhost:3000/auth/register", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify(formData), - credentials: 'include', // Include cookies in the request + credentials: "include", // Include cookies in the request }); if (response.status === 200) { // Registration successful setAuthenticated(true); setTimeout(() => { - navigate('/home'); // Redirect to /home after a small delay + navigate("/home"); // Redirect to /home after a small delay }, 500); } } } function fade_to_Auth() { - document.getElementById('Local')?.classList.add('fade-out-r-l'); - document.getElementById('Local-Backward')?.classList.add('fade-out-r-l'); + document.getElementById("Local")?.classList.add("fade-out-r-l"); + document.getElementById("Local-Backward")?.classList.add("fade-out-r-l"); setTimeout(() => { - setActivePage(['Auth', '']); - document.getElementById('Local')?.classList.remove('fade-out-r-l'); - document.getElementById('Local-Backward')?.classList.remove('fade-out-r-l'); + setActivePage(["Auth", ""]); + document.getElementById("Local")?.classList.remove("fade-out-r-l"); + document + .getElementById("Local-Backward") + ?.classList.remove("fade-out-r-l"); }, 475 /*fade-out-r-l*/); } @@ -96,19 +98,42 @@ export default function Local({ setAuthenticated, setActivePage, method }) {
-
{method === 'Login' ? 'Login To Your Account' : 'Register A New Account'}
+
+ {method === "Login" + ? "Login To Your Account" + : "Register A New Account"} +
{/* Username input (only for register method) */} - {method !== 'Login' && } + {method !== "Login" && ( + + )} {/* Email or username input */} - + {/* Password input */} - + {/* Forgot Password link (only for login method) */} - {method === 'Login' &&

Forgot Password?

} + {method === "Login" && ( +

Forgot Password?

+ )} {/* Submit button */}
- + { - setPlaceholderValue(''); + setPlaceholderValue(""); }} - onBlur={() => setPlaceholderValue('Search Here')} + onBlur={() => setPlaceholderValue("Search Here")} placeholder={placeholderValue} /> - {isSearching ? : } + {isSearching ? ( + + ) : ( + + )}
); }; diff --git a/client/src/pages/Home/LeftBar.jsx b/client/src/pages/Home/LeftBar.jsx index 512ec41..0b31ced 100644 --- a/client/src/pages/Home/LeftBar.jsx +++ b/client/src/pages/Home/LeftBar.jsx @@ -1,7 +1,13 @@ -import { faBars, faBell, faGear, faMessage, faUser } from '@fortawesome/free-solid-svg-icons'; -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { useContext } from 'react'; -import IsSearchingContext from '../../Contexts/IsSearchingContext'; +import { + faBars, + faBell, + faGear, + faMessage, + faUser, +} from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { useContext } from "react"; +import IsSearchingContext from "../../Contexts/IsSearchingContext"; const LeftBar = () => { const { setIsSearching } = useContext(IsSearchingContext); @@ -13,7 +19,12 @@ const LeftBar = () => { <>
- + diff --git a/client/src/pages/Home/MessageComponents/ChatContainerComponent.jsx b/client/src/pages/Home/MessageComponents/ChatContainerComponent.jsx index 24d7723..8882811 100644 --- a/client/src/pages/Home/MessageComponents/ChatContainerComponent.jsx +++ b/client/src/pages/Home/MessageComponents/ChatContainerComponent.jsx @@ -1,28 +1,32 @@ -import { faFaceLaugh, faImage, faRightLong } from '@fortawesome/free-solid-svg-icons'; -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { + faFaceLaugh, + faImage, + faRightLong, +} from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; const ChatContainerComponent = () => { let conversation = [ { - msgSender: 'You', - msgText: 'Adi bumbum', + msgSender: "You", + msgText: "Adi bumbum", date: new Date(), }, { - msgSender: 'Adi', - msgText: 'my bumbum', + msgSender: "Adi", + msgText: "my bumbum", }, { - msgSender: 'Adi', - msgText: 'sad', + msgSender: "Adi", + msgText: "sad", }, { - msgSender: 'You', - msgText: 'noice', + msgSender: "You", + msgText: "noice", }, { - msgSender: 'Adi', - msgText: 'hello', + msgSender: "Adi", + msgText: "hello", }, ]; @@ -30,7 +34,8 @@ const ChatContainerComponent = () => { const renderedMessages = []; for (let i = 0; i < conversation.length; i++) { - const messageClassName = conversation[i].msgSender === 'You' ? 'my-msg' : 'receiving-msg'; + const messageClassName = + conversation[i].msgSender === "You" ? "my-msg" : "receiving-msg"; const renderedMessage = (
diff --git a/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx b/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx index 80e562e..d08e7bd 100644 --- a/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx +++ b/client/src/pages/Home/MessageComponents/ChatInfoButtons.jsx @@ -1,28 +1,33 @@ -import { faMagnifyingGlass, faPhone, faUser, faVideo } from '@fortawesome/free-solid-svg-icons' -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' -import React from 'react' +import { + faMagnifyingGlass, + faPhone, + faUser, + faVideo, +} from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import React from "react"; const ChatInfoButtons = () => { - return ( - <> -
- -

Profile

-
-
- -

Voice Call

-
-
- -

Video Call

-
-
- - -
- - ) -} + return ( + <> +
+ +

Profile

+
+
+ +

Voice Call

+
+
+ +

Video Call

+
+
+ + +
+ + ); +}; -export default ChatInfoButtons +export default ChatInfoButtons; diff --git a/client/src/pages/Home/MessageComponents/ChatMenu.jsx b/client/src/pages/Home/MessageComponents/ChatMenu.jsx index 5d88d43..3201ced 100644 --- a/client/src/pages/Home/MessageComponents/ChatMenu.jsx +++ b/client/src/pages/Home/MessageComponents/ChatMenu.jsx @@ -1,65 +1,76 @@ -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'; -import ChatInfoButtons from './ChatInfoButtons'; +import ChatContainerComponent from "./ChatContainerComponent"; +import ChatInfoButtons from "./ChatInfoButtons"; const ChatMenu = () => { let userChats = { - friend: 'Aditya', - message: 'hello', - status: 'Online', + friend: "Aditya", + message: "hello", + status: "Online", picture: - 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEhUSDw8VFRUVFRcVFxUVFQ8VFRcXFRUXFxUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0NFQ8PFS0dFR0tLS0tLS0tLS0tKy0tLS0tLS0tLTctLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS03LS0tLf/AABEIAOEA4QMBIgACEQEDEQH/xAAXAAEBAQEAAAAAAAAAAAAAAAAAAQIF/8QAIBABAQEAAQQCAwAAAAAAAAAAAAERQRLB0fAhMQKBof/EABcBAQEBAQAAAAAAAAAAAAAAAAABAgb/xAAZEQEBAQADAAAAAAAAAAAAAAAAEQEhMUH/2gAMAwEAAhEDEQA/AOoKRxDu0FAQi4AmqlAURQBFEDui6AAAAAAAACgLQEWGAFQF6hNECggKAAQAAoKACBT3+lAABBQEFBUFAQ0UQ0lQwFEKCiYAuIaCqmgC1AA0RQUQBRABUANVKUFEUAEoiggKIoFEAWEAUEURMF1ARQgp5EUApEBYAACUFAA0icLQFQBRKAKhQAAFQgi0AEVFAEwFAWggoCCwBBQEKpgJAUEFAEWACKCCKAgoCCgoimCIqKKmi/pCClAQEUCBoAAAAAAABQAoAAAAAAAAAGgAAGogVYqoAoaAERcIgFgAAAigAFAAAIAAQgAAAAAAAAJ0CoKCgiKgKsvw0wq1FVNXWuEMZq6iaoAyBAALeQgAi0AAAAAAACAAaCYNYC1kUAQAFEBQBAAAwAKAAIoIoAAAAAAAEAAKAwrXwC1APIAQBUUBKtRQRQBFARABVAEDEigCFBQQFAAAAABlV6UFoAAAAEABUBQBBBQEKopCgIAAgqCigIAAAAAoCGgqAoAAIoAigIAABQAAAAAAAIoIAAAAAAABgCqiiIKAAAAAIFCgAAAAAKAqIEAAAAAAAAABdDEARQUAggAAAoAAAAFVAUoUEFRAUFwJEaSruAijIIKCFUADUXgIT6BBSIKHCgCAAtL9gCFAFqXsANICh5SAyLPBEFGpx7yfkDW9IhAZVOGqgBCgeAAD/9k=', + "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEhUSDw8VFRUVFRcVFxUVFQ8VFRcXFRUXFxUVFRUYHSggGBolHRUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0NFQ8PFS0dFR0tLS0tLS0tLS0tKy0tLS0tLS0tLTctLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS03LS0tLf/AABEIAOEA4QMBIgACEQEDEQH/xAAXAAEBAQEAAAAAAAAAAAAAAAAAAQIF/8QAIBABAQEAAQQCAwAAAAAAAAAAAAERQRLB0fAhMQKBof/EABcBAQEBAQAAAAAAAAAAAAAAAAABAgb/xAAZEQEBAQADAAAAAAAAAAAAAAAAEQEhMUH/2gAMAwEAAhEDEQA/AOoKRxDu0FAQi4AmqlAURQBFEDui6AAAAAAAACgLQEWGAFQF6hNECggKAAQAAoKACBT3+lAABBQEFBUFAQ0UQ0lQwFEKCiYAuIaCqmgC1AA0RQUQBRABUANVKUFEUAEoiggKIoFEAWEAUEURMF1ARQgp5EUApEBYAACUFAA0icLQFQBRKAKhQAAFQgi0AEVFAEwFAWggoCCwBBQEKpgJAUEFAEWACKCCKAgoCCgoimCIqKKmi/pCClAQEUCBoAAAAAAABQAoAAAAAAAAAGgAAGogVYqoAoaAERcIgFgAAAigAFAAAIAAQgAAAAAAAAJ0CoKCgiKgKsvw0wq1FVNXWuEMZq6iaoAyBAALeQgAi0AAAAAAACAAaCYNYC1kUAQAFEBQBAAAwAKAAIoIoAAAAAAAEAAKAwrXwC1APIAQBUUBKtRQRQBFARABVAEDEigCFBQQFAAAAABlV6UFoAAAAEABUBQBBBQEKopCgIAAgqCigIAAAAAoCGgqAoAAIoAigIAABQAAAAAAAIoIAAAAAAABgCqiiIKAAAAAIFCgAAAAAKAqIEAAAAAAAAABdDEARQUAggAAAoAAAAFVAUoUEFRAUFwJEaSruAijIIKCFUADUXgIT6BBSIKHCgCAAtL9gCFAFqXsANICh5SAyLPBEFGpx7yfkDW9IhAZVOGqgBCgeAAD/9k=", }; 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 ( <> -
-
-
- -
-
{userChats.friend}
-

{userChats.status}

+
+
+
+ +
+
{userChats.friend}
+

{userChats.status}

+
+
+
+ + +
-
- - - +
+
-
- -
-
-
- +
+

{userChats.friend}

- - ); }; diff --git a/client/src/pages/Home/MessageMenu.jsx b/client/src/pages/Home/MessageMenu.jsx index fee1894..e9918cf 100644 --- a/client/src/pages/Home/MessageMenu.jsx +++ b/client/src/pages/Home/MessageMenu.jsx @@ -1,5 +1,5 @@ -import DirectAccess from './DirectAccess'; -import ChatMenu from './MessageComponents/ChatMenu'; +import DirectAccess from "./DirectAccess"; +import ChatMenu from "./MessageComponents/ChatMenu"; const MessageMenu = () => { 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")} + > Profile

{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")} + > Profile

{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) => {
- profile picture + profile picture
- +

{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 e979549..880a7f6 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 d9fdbbe..8a19165 100644 --- a/client/src/pages/Home/normalChats.jsx +++ b/client/src/pages/Home/normalChats.jsx @@ -1,9 +1,9 @@ // import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons"; // import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { useContext, useState } from 'react'; -import UserContext from '../../Contexts/userContext'; +import { useContext, useState } from "react"; +import UserContext from "../../Contexts/userContext"; -import { useEffect } from 'react'; +import { useEffect } from "react"; const NormalChats = () => { const [connectionsArr, setConnectionsArr] = useState([]); @@ -14,15 +14,18 @@ const NormalChats = () => { }, []); const searchConnections = async function () { - const response = await fetch('http://localhost:3000/connection/searchConnections', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', + const response = await fetch( + "http://localhost:3000/connection/searchConnections", + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + id: user._id, + }), }, - body: JSON.stringify({ - id: user._id, - }), - }); + ); const data = await response.json(); const connectionsId = []; for (let i = 0; i < data.length; i++) { @@ -36,7 +39,9 @@ const NormalChats = () => { const tmpArr = []; for (let i = 0; i < connectionsId.length; i++) { - const response = await fetch(`http://localhost:3000/user/${connectionsId[i]}`); + const response = await fetch( + `http://localhost:3000/user/${connectionsId[i]}`, + ); const userData = await response.json(); tmpArr.push(userData); } @@ -47,7 +52,7 @@ const NormalChats = () => { function truncateText(text, maxLength) { if (text.length > maxLength) { - return text.substring(0, maxLength) + '...'; + return text.substring(0, maxLength) + "..."; } return text; } @@ -66,12 +71,17 @@ const NormalChats = () => { for (let i = 0; i < connectionsArr.length; i++) { renderedChats.push(
- Profile + Profile
-

{truncateText(connectionsArr[i].data.user.displayName, 18)}

+

+ {truncateText(connectionsArr[i].data.user.displayName, 18)} +

default text

-
+
, ); } @@ -79,9 +89,9 @@ const NormalChats = () => { }; 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/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 7967cdc..25f5262 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 d6d8548..16ae2e8 100644 --- a/server/index.js +++ b/server/index.js @@ -36,7 +36,7 @@ const store = new MongoDBStore({ }); // Handle errors from the session store -store.on(`error`, function(error) { }); +store.on(`error`, function (error) {}); // Configure session middleware const sessionConfig = { @@ -71,7 +71,7 @@ app.use(passport.session()); app.get( "http://localhost:8000/home", passport.authenticate("local"), - (req, res) => { } + (req, res) => {}, ); // Route handlers for user-related functionality @@ -83,7 +83,6 @@ app.use("/auth", authRoutes); // Route handlers for connection-related functionality app.use("/connection", connectionRoutes); - // Route handlers for google authentication related functionality app.use("/", googleRoutes); 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/store.js b/server/store.js index 47845f8..dde99df 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"); diff --git a/server/userSeed.js b/server/userSeed.js index a9cc772..c1a533e 100644 --- a/server/userSeed.js +++ b/server/userSeed.js @@ -1,9 +1,9 @@ -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"); // 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 +13,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 = 10000; // 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 +66,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(); }