Skip to content

Commit

Permalink
feat: enforces frontend route projection
Browse files Browse the repository at this point in the history
  • Loading branch information
SilveerDusk committed Jun 2, 2024
1 parent 3a33d2a commit fd6c6d0
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 38 deletions.
25 changes: 22 additions & 3 deletions frontend/lib/deletes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ export const handleDeleteItem = async (itemId: string) => {
try {
const response = await fetch(`${vite_backend_url}/items/${itemId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
});
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
Expand Down Expand Up @@ -82,7 +85,12 @@ export const handleDeleteGroupFromUsers = async (
try {
// Iterate over each userId
for (const userId of userIds) {
const response = await fetch(`${vite_backend_url}/users/${userId}`);
const response = await fetch(`${vite_backend_url}/users/${userId}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
if (response.ok) {
const user = await response.json();
const userGroups = user.groups;
Expand All @@ -100,6 +108,7 @@ export const handleDeleteGroupFromUsers = async (
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ groups: updatedGroups }),
},
Expand All @@ -124,7 +133,12 @@ export const handleDeleteBasketFromGroup = async (
basketId: string,
) => {
try {
const response = await fetch(`${vite_backend_url}/groups/${groupId}`);
const response = await fetch(`${vite_backend_url}/groups/${groupId}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
if (response.ok) {
const group = await response.json();
const groupBaskets = group.baskets;
Expand All @@ -144,6 +158,7 @@ export const handleDeleteBasketFromGroup = async (
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ baskets: updatedBaskets }),
},
Expand All @@ -165,7 +180,11 @@ export const handleDeleteBasketFromGroup = async (
export const handleDeleteAllItemsInBasket = async (basketId: string) => {
try {
// Fetch all items in the basket
const response = await fetch(`${vite_backend_url}/baskets/${basketId}`);
const response = await fetch(`${vite_backend_url}/baskets/${basketId}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
});
if (!response.ok) {
throw new Error(`Error fetching items: ${response.statusText}`);
}
Expand Down
11 changes: 11 additions & 0 deletions frontend/lib/edits.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,14 @@ export const addUserToGroup = async (group: IGroup, users: ObjectId[]) => {
body: JSON.stringify({ members: users }),
});
};

export const addFriendToUser = async (user: IUser, updatedFriends: ObjectId[]) => {
return fetch(`${vite_backend_url}/users/${user._id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
body: JSON.stringify({ friends: updatedFriends }),
});
}
14 changes: 12 additions & 2 deletions frontend/lib/fetches.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,21 @@ export const fetchGroupById = async (groupId: string) => {
};

export const fetchGroup = async (groupId: string) => {
return fetch(`${vite_backend_url}/groups/${groupId}`);
return fetch(`${vite_backend_url}/groups/${groupId}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
};

export const fetchUser = async (userId: ObjectId) => {
return fetch(`${vite_backend_url}/users/${userId}`);
return fetch(`${vite_backend_url}/users/${userId}`, {
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
},
}
);
};

export const fetchUserWithString = async (userId: string) => {
Expand Down
30 changes: 12 additions & 18 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import SignupPage from "./pages/SignupPage";
import ItemsPage from "./pages/ItemsPage";
import NavbarSignedOut from "./components/NavbarSignedOut";
import NavbarSignedIn from "./components/NavbarSignedIn";
import Friends_List from "./components/Friends_List_Component";
import ProfilePage from "./pages/ProfilePage";
import GroupPage from "./pages/MyGroupsPage";
import IndividualGroupPage from "./pages/IndividualGroupPage";
Expand Down Expand Up @@ -84,27 +83,14 @@ function App() {
updateState={{ setUser, setToken }}
/>
) : (
<NavbarSignedOut />
<NavbarSignedOut/>
)}
<Routes>
<Route path="/" element={<MoveLetters />} />
<Route
path="/login"
element={<LoginPage updateState={{ setUser, setToken }} />}
/>
<Route
path="/FriendsList"
element={<Friends_List LoggedInUser={user ? user._id : ""} />}
/>
<Route
path="/profile"
element={
<ProfilePage
LoggedInUser={user ? user._id.toString() : ""}
avatarColor={avatarColor}
/>
}
/>
<Route
path="/signup"
element={
Expand All @@ -115,12 +101,14 @@ function App() {
}
/>
<Route
path="/groups/:groupId"
path="/profile"
element={
<IndividualGroupPage LoggedInUser={user} setUser={setUser} />
<ProfilePage
LoggedInUser={user ? user._id.toString() : ""}
avatarColor={avatarColor}
/>
}
/>
{/* added route for individual group page */}
<Route
path="/items"
element={<ItemsPage stateVariable={{ user, token }} />}
Expand All @@ -134,6 +122,12 @@ function App() {
/>
}
/>
<Route
path="/groups/:groupId"
element={
<IndividualGroupPage LoggedInUser={user} setUser={setUser} />
}
/>
</Routes>
</Box>
</Router>
Expand Down
17 changes: 5 additions & 12 deletions frontend/src/components/Friends_List_Component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ import {
fetchUser,
fetchUserGroupsByUser,
fetchUserFriendsByUser,
fetchUserWithString,
} from "../../lib/fetches";
import { removeFriendFromUserByFriendId } from "../../lib/deletes";
import { addFriendToGroup } from "../../lib/fetches";
import { ObjectId } from "mongoose";
import { addFriendToUser } from "../../lib/edits";

type Props = {
initialUserId?: string;
Expand Down Expand Up @@ -89,8 +91,8 @@ const Friends_List: React.FC<Props> = ({
if (userId == LoggedInUser) {
console.log("Cannot add yourself as friend");
} else {
const res = await fetch(`http://localhost:3001/users/${userId}`);
const res2 = await fetch(`http://localhost:3001/users/${LoggedInUser}`);
const res = await fetchUserWithString(userId);
const res2 = await fetchUser(LoggedInUser);
let user;
let friend;
if (res.ok && res2.ok) {
Expand All @@ -101,16 +103,7 @@ const Friends_List: React.FC<Props> = ({
user.friends.push(friend._id);
console.log("Pushed to list");

const updatedRes = await fetch(
`http://localhost:3001/users/${LoggedInUser}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ friends: user.friends }),
},
);
const updatedRes = await addFriendToUser(user, user.friends);
console.log("Past Patch");
if (updatedRes.ok) {
setFriends([...friends, friend]);
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/pages/IndividualGroupPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ const IndividualGroupPage: React.FC<Props> = ({

useEffect(() => {
console.log(`Loading: ${loading}`);
if (!LoggedInUser) {
navigate("/login");
}
if (groupId) {
fetchGroup(String(groupId))
.then((group) => {
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/pages/ItemsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ const ItemsPage: React.FC<Props> = ({
.catch((err) => {
console.log(`Terrible error occurred! ${err}`);
});
} else {
navigate("/login");
}
}, [stateVariable.user]);

Expand Down
6 changes: 4 additions & 2 deletions frontend/src/pages/MyGroupsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ import SkeletonGroup from "../components/SkeletonGroup";
import { IoIosSwap } from "react-icons/io";
import SearchBar from "../components/SearchBar";
import PageSelector from "../components/PageSelector";
import { Link } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import "../styles/MyGroups.css";
import NewGroupOptions from "../components/NewGroupOptions";

import { IGroup } from "../../../backend/models/groupSchema";
import { IUser } from "../../../backend/models/userSchema";
import { fetchGroups } from "../../lib/fetches";
Expand All @@ -42,6 +41,7 @@ const GroupPage: React.FC<Props> = ({
const [loading, setLoading] = useState(true);
const gridDims = [2, 4];
const skelIds: number[] = [];
const navigate = useNavigate();
for (let i = 0; i < gridDims[0] * gridDims[1]; i++) {
skelIds.push(i);
}
Expand Down Expand Up @@ -71,6 +71,8 @@ const GroupPage: React.FC<Props> = ({
.catch((err) => {
console.log(`Terrible error occurred! ${err}`);
});
} else {
navigate("/login");
}
}, [stateVariable.user]);

Expand Down
11 changes: 10 additions & 1 deletion frontend/src/pages/ProfilePage.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import React from "react";
import React, { useEffect } from "react";
import { Box, Grid, GridItem, Heading } from "@chakra-ui/react";
import UserProfile from "../components/UserProfile";
import Friends_List from "../components/Friends_List_Component";
import { useNavigate } from "react-router-dom";

interface ProfilePageProps {
LoggedInUser: string;
Expand All @@ -12,6 +13,14 @@ const ProfilePage: React.FC<ProfilePageProps> = ({
LoggedInUser,
avatarColor,
}) => {
const navigate = useNavigate();
useEffect(() => {
if (!LoggedInUser) {
navigate("/login");
}
}
);

return (
<Box bg="gray.100" color="gray.800" minH="93vh" p={4} overflowY={"auto"}>
<Grid
Expand Down

0 comments on commit fd6c6d0

Please sign in to comment.