Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

profile_page #139

Merged
merged 18 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions app/locations/[location]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,24 @@ import {
import { Location } from "@/interfaces/Location";
import { FrontEndReviews } from "@/interfaces/Review";

import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import { useCookies } from "react-cookie";

import LocationCategories from "@/components/location/categories";
import Link from "next/link";

export default function Page({ params }: { params: { location: number } }) {
const [location, setLocation] = useState<Location | null>(null);
const [foodReviews, setFoodReviews] = useState<FrontEndReviews | null>(null);
const [cookies] = useCookies(["userEmail"]);
const alertShown = useRef(false);

//const notificationsEnabled = cookies.notificationsEnabled === "true";
const notificationsEnabled =
localStorage.getItem("notificationsEnabled") === "true";

const user_email = cookies.userEmail || 'anonymous';
console.log(user_email);

useEffect(() => {
fetchLocations().then(async (locations: Location[]) => {
Expand All @@ -33,16 +43,39 @@ export default function Page({ params }: { params: { location: number } }) {
let username = "";
const userInfo = await fetchUserInfo();
username = userInfo.email;
console.log(username);

fetchFoodReviewsBulk({
food_names: food_names,
user_id: username,
user_id: user_email,
}).then((reviews: FrontEndReviews) => {
setLocation(location);
setFoodReviews(reviews);
});
});
}, [params.location]);
useEffect(() => {
if (
location &&
foodReviews &&
notificationsEnabled &&
!alertShown.current
) {
const favoriteFoods = Object.keys(foodReviews).filter(
(foodName) =>
user_email !== "anonymous" && foodReviews[foodName].user_rating === 5
);

if (favoriteFoods.length > 0) {
alert(
`One or more of your favorite foods are being served! Foods: ${favoriteFoods.join(
", "
)}`
);
alertShown.current = true;
}
}
}, [location, foodReviews, notificationsEnabled, user_email]);

if (!location || !foodReviews) {
return <h1>Loading...</h1>;
Expand Down
159 changes: 131 additions & 28 deletions app/profile/page.tsx
Original file line number Diff line number Diff line change
@@ -1,71 +1,174 @@
"use client";
import React from "react";
import { useEffect, useState } from "react";
import React, { useEffect, useState } from "react";
import { googleLogout } from "@react-oauth/google";
import axios from "axios";
import { fetchUserInfo } from "@/app/requests";
import { useCookies } from "react-cookie";
import {
fetchLocations,
fetchFoodReviewsBulk,
fetchUserInfo,
} from "@/app/requests";
import Image from "next/image";
import { FrontEndReviews } from "@/interfaces/Review";

interface User {
name: string;
email: string;
picture: string;
}
import Image from "next/image";

const imageWidth = 100;
const imageHeight = 100;

const Page = () => {
const [user, setUser] = useState<User | null>(null);
const getUserInfo = async () => {
try {
const userInfo = await fetchUserInfo();
setUser(userInfo);
} catch (error) {
console.error("Failed to fetch user info:", error);
}
};
const [cookies, setCookie, removeCookie] = useCookies([
"authToken",
"userEmail",
]);
const [reviews, setReviews] = useState<FrontEndReviews>({});
const [notificationsEnabled, setNotificationsEnabled] = useState(
localStorage.getItem("notificationsEnabled") === "true",
);
const [foodNames, setFoodNames] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const getUserInfo = async () => {
try {
const access_token = cookies.authToken;

if (!access_token) {
console.error("No access token found");
return;
}

const userInfo = await axios
.get("https://www.googleapis.com/oauth2/v3/userinfo", {
headers: { Authorization: `Bearer ${access_token}` },
})
.then((res) => res.data);

setUser({
name: userInfo.name,
email: userInfo.email,
picture: userInfo.picture,
});
setCookie("userEmail", userInfo.email, { path: "/" });
} catch (error) {
console.error("Error fetching user info:", error);
}
};
const getLocationsAndFoodNames = async () => {
try {
const locations = await fetchLocations();
const allFoodNames = locations.flatMap((location) =>
location.categories.flatMap((category) =>
category.sub_categories.flatMap((sub_category) =>
sub_category.foods.map((food) => food.name),
),
),
);
setFoodNames(allFoodNames);
console.log("Food Names:", allFoodNames);
} catch (error) {
console.error("Error fetching locations and food names:", error);
}
};
getUserInfo();
}, []);

getLocationsAndFoodNames();
}, [cookies.authToken, setCookie]);

const handleLogout = () => {
googleLogout();
axios
.post("http://localhost:8000/api/logout/")
.then((res) => console.log("Backend logout successful", res))
.catch((err) => console.error("Backend logout failed", err));

// Remove the token from sessionStorage
sessionStorage.removeItem("token");
// Redirect the user to the main page after logging out
removeCookie("authToken", { path: "/" });
removeCookie("userEmail", { path: "/" });
localStorage.removeItem("token");
window.location.href = "/";
console.log("Logged out successfully");
};
useEffect(() => {
if (user && user.email) {
fetchReviews(user.email);
}
}, [user, foodNames]);

const fetchReviews = async (userEmail: string) => {
try {
const reviews = await fetchFoodReviewsBulk({
food_names: foodNames,
user_id: userEmail,
});
const filteredReviews = Object.fromEntries(
Object.entries(reviews).filter(
([_, review]) => review.user_rating != null,
),
);
setReviews(filteredReviews);
setLoading(false);
console.log("Fetched Reviews:", filteredReviews);
} catch (error) {
console.error("Error fetching reviews:", error);
}
};

const toggleNotifications = () => {
const newState = !notificationsEnabled;
setNotificationsEnabled(newState);
localStorage.setItem("notificationsEnabled", newState.toString());

console.log(`Notifications are now ${newState ? "enabled" : "disabled"}`);
};

return (
<div>
<h1>Profile</h1>
<div className="flex flex-col items-center">
<h1 className="text-[#003C6C] font-medium text-xl">Profile</h1>
{user && (
<div>
<div className="flex flex-col items-center">
<Image
src={user.picture}
alt="User profile"
width={imageWidth}
height={imageHeight}
className="rounded-full border-4 border-[#003C6C]"
/>
<h2>
<h2 className="mt-2 text-center">
Welcome, {user.name} - {user.email}
</h2>
</div>
)}
<div className="w-full mt-5">
<h2 className="text-[#003C6C] font-medium text-xl text-center">
Your Food Reviews:
</h2>
{loading ? (
<h1 className="text-center">Loading...</h1>
) : (
<ul className="text-center bg-gray-100 p-4 rounded-lg">
{Object.entries(reviews).map(([food_name, review]) => (
<li key={food_name} className="mb-2 text-[#003C6C]">
<h3 className="font-bold">{food_name}</h3>
<p>Rating: {review.user_rating}</p>
</li>
))}
</ul>
)}
</div>
<button
onClick={toggleNotifications}
className="hover:underline decoration-yellow-400 underline-offset-8 m-5 p-2 text-[#003C6C] font-medium text-xl"
>
{notificationsEnabled
? "Disable Notifications"
: "Enable Notifications"}
</button>
<button
onClick={() => handleLogout()}
className="hover:underline decoration-yellow-400 underline-offset-8 top-0 right-0 m-5 p-2 text-[#003C6C] font-medium text-xl"
onClick={handleLogout}
className="hover:underline decoration-yellow-400 underline-offset-8 m-5 p-2 text-[#003C6C] font-medium text-xl"
>
Logout
</button>
</div>
);
};

export default Page;
4 changes: 2 additions & 2 deletions app/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export async function updateReview(data: {

export const fetchUserInfo = async () => {
try {
const access_token = sessionStorage.getItem("token");
const access_token = localStorage.getItem("token");

if (!access_token) {
throw new Error("No access token found in session storage.");
Expand All @@ -62,7 +62,7 @@ export const fetchUserInfo = async () => {
"https://www.googleapis.com/oauth2/v3/userinfo",
{
headers: { Authorization: `Bearer ${access_token}` },
}
},
);

const userInfo = response.data;
Expand Down
4 changes: 2 additions & 2 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ def validate_user(request):
# add user_info to database using get or create possibly

# add current user
current_user = CurrentUser(request.session)
request.session["current_user"] = user_info["email"]
# current_user = CurrentUser(request.session)
# request.session["current_user"] = user_info["email"]

except requests.RequestException as e:
return JsonResponse({"error": "Failed to validate access token"}, status=500)
Expand Down
12 changes: 11 additions & 1 deletion backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@

from pathlib import Path

from private.private_settings import DJANGO_SECRET_KEY, IS_DEV
from private.private_settings import (
DJANGO_SECRET_KEY,
IS_DEV,
)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = (
Expand All @@ -29,6 +32,7 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = IS_DEV


ALLOWED_HOSTS = [
"127.0.0.1",
"localhost",
Expand Down Expand Up @@ -61,6 +65,12 @@
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [
"authorization",
"content-type",
"Access-Control-Allow-Origin",
]

ROOT_URLCONF = "backend.urls"

Expand Down
23 changes: 21 additions & 2 deletions components/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
import React, { useEffect, useState } from "react";
import { GoogleOAuthProvider, useGoogleLogin } from "@react-oauth/google";
import axios from "axios";
import { useCookies } from "react-cookie";

import { GOOGLE_CLIENT_ID } from "@/private/secrets";

interface User {
Expand All @@ -18,21 +20,38 @@ const LoginPage = () => {
};

const LoginComponent = () => {
const [user, setUser] = useState<User | null>(null);
const [loggedIn, setLoggedIn] = useState(false);
const [cookies, setCookie] = useCookies(["authToken", "userEmail"]);

useEffect(() => {
console.log("LoginPage component mounted");
}, []);

const handleLogin = useGoogleLogin({
flow: "implicit",

onSuccess: (tokenResponse) => {
onSuccess: async (tokenResponse) => {
console.log(tokenResponse);
// Store authentication token in the browser's storage for navigation bar use
sessionStorage.setItem("token", tokenResponse.access_token);
localStorage.setItem("token", tokenResponse.access_token);
const expires = new Date();
expires.setHours(expires.getHours() + 3);
setCookie("authToken", tokenResponse.access_token, {
path: "/",
expires,
});
// Redirect the user to main page
window.location.href = "/";
//handleLoginSuccess
//client side authentication retrieve user info from access token
const userInfo = await axios
.get("https://www.googleapis.com/oauth2/v3/userinfo", {
headers: { Authorization: `Bearer ${tokenResponse.access_token}` },
})
.then((res) => res.data);
//console.log("userEmail:", userInfo.email);
setCookie("userEmail", userInfo.email, { path: "/", expires });
//send the token to backend
axios
.post("http://localhost:8000/api/users", {
Expand Down
Loading
Loading