Skip to content

Commit

Permalink
updated favlist page/updated save to favlist route
Browse files Browse the repository at this point in the history
  • Loading branch information
Ceiceiceii committed Dec 6, 2023
1 parent db0ee7a commit 87ab1a7
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 50 deletions.
16 changes: 2 additions & 14 deletions back-end/src/app.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,6 @@ const passwordValidationRules = [
// Optionally, include checks for special characters or uppercase letters
];

//check login status:
function isAuthenticated(req, res, next) {
console.log(req.session._id);
if (req.session.uuid) {
console.log(req.session._id);
next();
} else {
res.status(401).json({ message: 'Not authenticated' });
}
}



// routes that needs authentication
Expand All @@ -123,9 +112,8 @@ app.patch("/resetpassword", passwordValidationRules, resetpasswordRouter); //Fin
app.delete("/delaccount", delaccountRouter); //Finished

// Favorites list routes
app.post('/addFavorite', addFavListRouter);
// app.patch('/getfavlist', isAuthenticated, favListRouter);
app.post('/getfavlist', favListRouter);
app.post('/addFavorite', addFavListRouter);//finished
app.get('/getfavlist', favListRouter);
app.post('/getArts', getArts);//finished
app.get('/search', searchRouter);
// app.post('/favlist/remove',removeFavListRouter);
Expand Down
8 changes: 4 additions & 4 deletions back-end/src/models/User.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const userSchema = new Schema({
const userSchema = new mongoose.Schema({
uuid: {
type: String, // String type for the UUID
required: true
Expand All @@ -20,9 +20,9 @@ const userSchema = new Schema({
type: String, // String type for the hashed password
required: true
},
favorites: [{
type: mongoose.Schema.Types.Mixed, // Mixed type for an array of favorites, adjust as needed
}],
favorites: [
{type: mongoose.Schema.Types.Mixed}
],
__v: {
type: Number // Number type for the version key
}
Expand Down
26 changes: 15 additions & 11 deletions back-end/src/routes/modifyFavListRouter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Artwork from '../models/Artwork.mjs';
import { body, validationResult } from 'express-validator';
import jwt from 'jsonwebtoken';
import User from '../models/User.mjs';
import mongoose from 'mongoose';


export const getArts = async (req, res) => {
Expand Down Expand Up @@ -46,18 +47,16 @@ export const favListRouter = async (req, res) => {
const token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const userID = decoded.id;
const artID = req.body;

try {


const user = await User.findOne({ uuid: userID });

if (!user) {
return res.status(404).send({ message: 'User not found' });
}

const favorites = await Art.find({
console.log(user.favorites);
const favorites = await Artwork.find({
'_id': { $in: user.favorites }
});

Expand All @@ -72,7 +71,6 @@ export const favListRouter = async (req, res) => {

export const addFavListRouter = async (req, res) => {
// Check if the Authorization header is present
console.log(req.body);
if (!req.headers.authorization) {
return res.status(401).json({ message: "Authorization token is missing" });
}
Expand All @@ -81,26 +79,32 @@ export const addFavListRouter = async (req, res) => {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const userID = decoded.id;
const artID = req.body;
const objectId = mongoose.Types.ObjectId(artID);
console.log('uuid',userID);
try {

const user = await User.findOne({ uuid: userID });
if (!user) {
return res.status(404).send('User not found');
}

let isFavorited;
const index = user.favorites.indexOf(artID);
const index = user.favorites.findIndex(fav => fav.toString() === objectId.toString());

console.log(index);

console.log(user.favorites);
if (index > -1) {
user.favorites.splice(index, 1);
console.log('removed');
isFavorited = false;
} else {
// If the art is not in favorites, add it
user.favorites.push(artID)
await user.save();
// await User.findByIdAndUpdate(userID, { $addToSet: { favorites: artID } });
user.favorites.push(objectId);
isFavorited = true;
}


await user.save();
console.log(user.favorites);
res.status(200).json({ message: 'Favorites updated', isFavorited });
} catch (error) {
console.error('Error updating favorites', error);
Expand Down
22 changes: 6 additions & 16 deletions front-end/src/pages/FavoriteList/FavoriteList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,27 @@ import axiosProvider from "../../util/api/axios"
const FavoriteList = () => {
// const [favorites, setFavorites] = useState([]);
const [arts, setArts] = useState([]);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const navigate = useNavigate();
const location = useLocation();
//TODO:


useEffect(() => {
const userUUID = localStorage.getItem('uuid');
console.log(userUUID);
if (userUUID) {
// Optionally, add more robust checks here, like validating the UUID with the server
setIsLoggedIn(true);
fetchFavoriteArts(userUUID);
} else {
setIsLoggedIn(false);
}
fetchFavoriteArts();
}, []);

const fetchFavoriteArts = async (uuid) => {
const fetchFavoriteArts = async () => {
try {
const response = await axiosProvider.get(`/getfavlist`, { params: { uuid } });
const response = await axiosProvider.get('/getfavlist');
setArts(response.data);
console.log(arts);
} catch (error) {
console.error("Error fetching favorite arts:", error);
setArts([]);
}
};


const sortArts = (criteria) => {
if (criteria === "name") {
if (criteria === "title") {
setArts(prevArts => [...prevArts].sort((a, b) => a.name.localeCompare(b.name)));
} else if (criteria === "Year") {
setArts(prevArts => [...prevArts].sort((a, b) => a.year - b.year));
Expand Down Expand Up @@ -74,7 +64,7 @@ const FavoriteList = () => {

<div className='mt-5'>
{arts.map((art) => (
<div key={art.id} onClick={() => handleArtItemClick(art.id)}>
<div key={art._id} onClick={() => handleArtItemClick(art.id)}>
<ArtItem art={art}/>
</div>
))}
Expand Down
5 changes: 3 additions & 2 deletions front-end/src/pages/InfoDetail/InfoDetail.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import LeftBtn from "../../components/common/leftBtn"

const InfoDetail = (props) => {
// parameters: pic, name, subtitle(string array), parag
const dummyPic = "https://picsum.photos/200"
const dummyPic = props.url;
console.log(dummyPic);
const dummyName = "error header"
const dummySubtitle = ["Author: some author", "Time: some time", "Location: some location"]
const dummyparag = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. "
Expand All @@ -18,7 +19,7 @@ const InfoDetail = (props) => {
<LeftBtn />
</NavBar>
<div className="max-h-[80vh] max-w-full mx-auto flex">
<img className="object-contain" src={props.pic ?? dummyPic} alt="picture" />
<img className="object-contain" src={props.url ?? dummyPic} alt="picture" />
</div>
<div className="w-[80%] mb-[10%] mx-auto max-w-[30rem]">
<div className="mt-2">
Expand Down
6 changes: 3 additions & 3 deletions front-end/src/pages/MainMap/popupSearch.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ const PopupSearch = (props) => {
if (props.refreshPopup) getData();
}, [props.refreshPopup, props.foundData]);

const handleArtItemClick = (artId) => {
const handleArtItemClick = (art) => {
// Navigate to the art information page
navigate("/info", { state: { from: location.pathname } });
navigate("/info");
};


Expand Down Expand Up @@ -75,7 +75,7 @@ const PopupSearch = (props) => {

<div className="flex flex-row gap-8 overflow-scroll p-8">
{arts.map((art) => (
<div key={art._id} onClick={() => handleArtItemClick(art.id)}>
<div key={art._id} onClick={(art) => handleArtItemClick(art)}>
<div>
<ArtItem art={art} />
</div>
Expand Down

0 comments on commit 87ab1a7

Please sign in to comment.