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

updatedSaveFavFunction/changed userSchema/changed backend/frontend of… #171

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
31 changes: 14 additions & 17 deletions back-end/src/app.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import delaccountRouter from './routes/delaccountRouter.mjs';
import getpieceRouter from './routes/getpieceRouter.mjs';
import resetpasswordRouter from './routes/resetpasswordRouter.mjs';
import resetemailRouter from './routes/resetemailRouter.mjs';

import searchRouter from './routes/searchRouter.mjs';

import {addFavListRouter,favListRouter, getArts} from './routes/modifyFavListRouter.mjs'
import { configDotenv } from 'dotenv';
Expand Down Expand Up @@ -102,18 +102,15 @@ const passwordValidationRules = [
];

//check login status:
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];

if (token == null) return res.status(401).json({ message: 'No token provided' });

jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ message: 'Token is not valid' });
req.user = user;
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' });
}
}



Expand All @@ -126,11 +123,11 @@ app.patch("/resetpassword", passwordValidationRules, resetpasswordRouter); //Fin
app.delete("/delaccount", delaccountRouter); //Finished

// Favorites list routes
// app.get('/getfavlist', favListRouter);
// app.post('/favlist/add',addFavListRouter);
app.patch('/addFavorite', authenticateToken, addFavListRouter);
app.patch('/getfavlist', authenticateToken, favListRouter);
app.post('/getArts', getArts);
app.post('/addFavorite', addFavListRouter);
// app.patch('/getfavlist', isAuthenticated, favListRouter);
app.post('/getfavlist', favListRouter);
app.post('/getArts', getArts);//finished
app.get('/search', searchRouter);
// app.post('/favlist/remove',removeFavListRouter);

// export the express app we created to make it available to other modules
Expand Down
43 changes: 4 additions & 39 deletions back-end/src/models/Artwork.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const artworkSchema = new Schema({
_id: {
type: mongoose.Schema.Types.ObjectId, // Object ID type for MongoDB
required: true
},
url: String,
Year: {
$numberInt: String
Expand Down Expand Up @@ -35,42 +39,3 @@ artworkSchema.index({ 'geoLocation': '2dsphere' });

const Artwork = model('Artwork', artworkSchema, 'arts');
export default Artwork;


// // Import statements
// import mongoose from 'mongoose';

// // Schema definition
// const EventSchema = new mongoose.Schema({
// id: {
// type: String,
// unique: true,
// required: true,
// },
// location: {
// type: String,
// required: true,
// },
// name: {
// type: String,
// required: true,
// },
// author: {
// type: String,
// required: true,
// },
// year: {
// type: Number,
// required: true,
// },
// url: {
// type: String,
// required: true,
// },
// });

// // Model creation
// const Event = mongoose.model('Event', EventSchema);

// // Export the model
// export default Event;
53 changes: 27 additions & 26 deletions back-end/src/models/User.mjs
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const UserSchema = new mongoose.Schema({
uuid: {
type: String,
unique: true,
required: true,
},
name: {
type: String,
required: true,
},
email: {
type: String,
lowercase: true,
required: true,
},
password: {
type: String,
required: true,
select: false, // hide password by default
},
favorites: {
type: Array,
required: false,
},
const userSchema = new Schema({
uuid: {
type: String, // String type for the UUID
required: true
},
name: {
type: String, // String type for the name
required: true
},
email: {
type: String, // String type for the email
required: true,
unique: true, // Assuming email should be unique
match: [/.+\@.+\..+/, 'Please fill a valid email address'] // Regex for email validation
},
password: {
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
}],
__v: {
type: Number // Number type for the version key
}
});

const User = mongoose.model('User', UserSchema);

const User = model('User', userSchema,'users');
export default User;
87 changes: 41 additions & 46 deletions back-end/src/routes/modifyFavListRouter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ export const getArts = async (req, res) => {
try {
const artworks = await Artwork.find({
Year: { $gte: startYear, $lte: endYear },
// "latitude": location.latitude,
// "longitude": location.longitude
geoLocation: {
$near: {
$geometry: {
Expand All @@ -40,10 +38,20 @@ export const getArts = async (req, res) => {


export const favListRouter = async (req, res) => {

if (!req.headers.authorization) {
return res.status(401).json({ message: "Authorization token is missing" });
}

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 userUuid = req.params.uuid;

const user = await User.findOne({ uuidd: userUuid });

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

if (!user) {
return res.status(404).send({ message: 'User not found' });
Expand All @@ -61,55 +69,42 @@ export const favListRouter = async (req, res) => {
};


// export const addFavListRouter = (req, res) => {
// const artToUpdate = req.body;

// const artIndex = arts.findIndex(art => art.id === artToUpdate.id);

// if (artIndex > -1) {
// arts[artIndex].inFavList = !arts[artIndex].inFavList;
// res.status(200).json(arts[artIndex]);
// } else {
// res.status(404).send('Art not found');
// }
// };

export const addFavListRouter = async (req, res) => {
// const { userUUID, artUUID } = req.body;

// try {
// const user = await UserModel.findOne({ "_id": userUUID });

// if (!user) {
// return res.status(404).send('User not found');
// }
// const isFavorite = user.favorites.includes(artUUID);

// if (isFavorite) {
// // already a favorite, remove it from the favorites array
// user.favorites = user.favorites.filter(fav => fav !== artUUID);
// await user.save(); // Save the updated user document
// } else {

// user.favorites.push(artUUID);
// await user.save();
// }

// res.status(200).json(user);
// } catch (error) {
// console.error("Error updating favorite list:", error);
// res.status(500).send('Internal Server Error');
// }
const userId = req.user.uuid;
// 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" });
}

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.findById(userId).populate('favorites');
const user = await User.findOne({ uuid: userID });
if (!user) {
return res.status(404).send('User not found');
}

if (!user) return res.status(404).json({ message: "User not found." });
let isFavorited;
const index = user.favorites.indexOf(artID);
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 } });
isFavorited = true;
}

res.json(user.favorites);
res.status(200).json({ message: 'Favorites updated', isFavorited });
} catch (error) {
res.status(500).json({ message: "Internal server error." });
console.error('Error updating favorites', error);
res.status(500).send('Error updating favorites');
}
};

Expand Down
30 changes: 30 additions & 0 deletions back-end/src/routes/searchRouter.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import Artwork from '../models/Artwork.mjs';

export const searchRouter = async (req, res) => {

const { query } = req.query;

try {
let searchQuery = {};

if (query) {
searchQuery = {
$or: [
{ Year: query },
{ artist: { $regex: query, $options: 'i' } },
{ title: { $regex: query, $options: 'i' } },
{ location: { $regex: query, $options: 'i' } }
]
};
}

const artworks = await Artwork.find(searchQuery).limit(10);
res.json(artworks);
} catch (error) {
res.status(500).json({ message: "Internal server error." });
}
};

export default searchRouter;


Loading