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

Onrender #17

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
3,224 changes: 1,622 additions & 1,602 deletions packages/backend/package-lock.json

Large diffs are not rendered by default.

54 changes: 28 additions & 26 deletions packages/backend/package.json
Original file line number Diff line number Diff line change
@@ -1,28 +1,30 @@
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.1",
"typescript": "^5.2.2"
},
"dependencies": {
"axios": "^1.6.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"config": "^3.3.9",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.17.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.0",
"uga-geoguessr": "file:../.."
}
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./src/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.17.1",
"typescript": "^5.2.2"
},
"dependencies": {
"axios": "^1.6.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"config": "^3.3.9",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.17.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.0",
"node-cron": "^3.0.3",
"uga-geoguessr": "file:../.."
}
}
2 changes: 0 additions & 2 deletions packages/backend/src/models/User.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
firstName: { required: true, type: String, trim: true },
lastName: { required: true, type: String, trim: true },
username: { required: true, type: String, trim: true },
email: { required: true, type: String, unique: true, trim: true },
password: { required: true, type: String, minLength: 8 },
Expand Down
64 changes: 56 additions & 8 deletions packages/backend/src/routes/api/games.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ router.get("/:id", async (req, res) => {
res.status(500).json({ msg: "Error fetching data" });
}
});

let numgamesfinished = 0;
router.put("/:id", async (req, res) => {
try {
let { score, percentage, distance, selectedCoordinate, answerLocation, nextStage } = req.body;
Expand All @@ -44,7 +44,8 @@ router.put("/:id", async (req, res) => {

if (nextStage === foundGame.numberOfStages) {
result = await Games.findByIdAndDelete(req.params.id);
console.log(`GAME ${foundGame._id} FINISHED AND DELETED`);
numgamesfinished += 1;
console.log(`GAME ${foundGame._id} FINISHED AND DELETED -- ${"total " + numgamesfinished}`);

const token = req.header("x-auth-token");
if (token) {
Expand Down Expand Up @@ -84,7 +85,12 @@ router.post("/", async (req, res) => {
throw new Error("Invalid number of stages");
}
let gameTypeInfo;
if (gameType._id === "default01" || gameType._id === "default02" || gameType._id === "default03") {
if (
gameType._id === "default01" ||
gameType._id === "default02" ||
gameType._id === "default03" ||
gameType._id === "default04"
) {
gameTypeInfo = defaultgameTypes.find((obj) => obj.id.toString() === gameType._id.toString());
} else {
gameTypeInfo = await GameTypes.findById(gameType._id);
Expand Down Expand Up @@ -128,7 +134,6 @@ router.post("/", async (req, res) => {
difficulty,
update_date: new Date(),
};

const createdGame = await Games.create(newGame);
const token = req.header("x-auth-token");
if (token) {
Expand All @@ -139,15 +144,14 @@ router.post("/", async (req, res) => {
const updateUser = await User.findByIdAndUpdate(verified.id, user);
}
}

console.log(`--- NEW GAME ${createdGame._id} CREATED ---`);
numberofgamesplayed += 1;
console.log(`--- NEW GAME ${createdGame._id} CREATED --- ${"total " + numberofgamesplayed}`);
res.json(`/game/${createdGame._id}`);
} catch (error) {
//console.error(error);
res.status(500).json({ msg: `Error: ${error.message} ` });
}
});

let numberofgamesplayed = 0;
router.delete("/:id", async (req, res) => {
try {
const deletedGame = await Games.findByIdAndDelete(req.params.id);
Expand Down Expand Up @@ -250,4 +254,48 @@ const defaultgameTypes = [
{ lat: 33.942241808473824, lng: -83.37007146324335, radius: 167.35036594040082 },
],
},
{
id: "default04",
default: true,
title: "The UGA Parking Experience",
description: "See the parking spots youll never have",
url: "https://cdn.discordapp.com/attachments/1054239396024549486/1192546702775824565/5b7ea6f8483a0.image.jpg?ex=65a978aa&is=659703aa&hm=a0925fce7e34c1250d7f96704516fe291e232f0848776a4e3be95c3d23c27736&",
possibleCoordinates: [
{ lat: 33.938087490114796, lng: -83.36935958581721, radius: 114 },
{ lat: 33.9361885759344, lng: -83.36194471735513, radius: 118 },
{ lat: 33.933434872247474, lng: -83.3719976943281, radius: 142 },
{ lat: 33.94126639695296, lng: -83.37910355442307, radius: 79 },
{ lat: 33.941445429072694, lng: -83.37764525015562, radius: 82 },
{ lat: 33.94172211433498, lng: -83.37653134028794, radius: 40 },
{ lat: 33.94189444781422, lng: -83.37176678355839, radius: 42 },
{ lat: 33.94212748987915, lng: -83.37257712767213, radius: 55 },
{ lat: 33.94327327031592, lng: -83.37357271882571, radius: 50 },
{ lat: 33.94541469740451, lng: -83.37070366911718, radius: 56 },
{ lat: 33.9460602648484, lng: -83.37079522185844, radius: 55 },
{ lat: 33.94455580259811, lng: -83.3714066535213, radius: 46 },
{ lat: 33.94703894608532, lng: -83.37366000169206, radius: 34 },
{ lat: 33.9466971796248, lng: -83.37443819992485, radius: 19 },
{ lat: 33.943666740637674, lng: -83.37924800882142, radius: 40 },
{ lat: 33.948639218054616, lng: -83.38154156817734, radius: 106 },
{ lat: 33.948435399670764, lng: -83.38252437069929, radius: 114 },
{ lat: 33.94873012253796, lng: -83.37959680355652, radius: 45 },
{ lat: 33.950171441029006, lng: -83.3766526804705, radius: 19 },
{ lat: 33.95019733775513, lng: -83.37703946987946, radius: 17 },
{ lat: 33.950127251343176, lng: -83.37772722276367, radius: 62 },
{ lat: 33.95269727862853, lng: -83.37890073065181, radius: 72 },
{ lat: 33.956106605016714, lng: -83.37254279648862, radius: 73 },
{ lat: 33.95524917392448, lng: -83.37184436448504, radius: 40 },
{ lat: 33.956738765413085, lng: -83.3730298550244, radius: 52 },
{ lat: 33.93811658941526, lng: -83.36929318213429, radius: 110 },
{ lat: 33.93585914261665, lng: -83.36190221691228, radius: 67 },
{ lat: 33.93037767751633, lng: -83.36586001093772, radius: 93 },
{ lat: 33.93322895963708, lng: -83.37214403512186, radius: 107 },
{ lat: 33.940792362571656, lng: -83.36752916195157, radius: 67 },
{ lat: 33.93985185469944, lng: -83.36721228447567, radius: 69 },
{ lat: 33.93913055255685, lng: -83.3679155183562, radius: 65 },
{ lat: 33.939142421510226, lng: -83.36670042283215, radius: 52 },
{ lat: 33.93935258798488, lng: -83.36616043949799, radius: 51 },
{ lat: 33.9338197668977, lng: -83.37088295125416, radius: 80 },
],
},
];
19 changes: 6 additions & 13 deletions packages/backend/src/routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ dotenv.config();
const JWT_SECRET_KEY = process.env.JWT_SECRET_KEY; // Replace with a secure secret key
userRouter.post("/signup", async (req, res) => {
try {
const { firstName, lastName, email, password, confirmPassword, username } = req.body;
if (!firstName || !lastName || !email || !password || !username || !confirmPassword) {
let { email, password, confirmPassword, username } = req.body;
if (!email || !password || !username || !confirmPassword) {
return res.status(400).json({ msg: "Please fill in all fields." });
}

email = email.toLowerCase();
username = username.toLowerCase();
// Password validation
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
const hasUppercase = /[A-Z]/.test(password);
Expand All @@ -39,8 +40,6 @@ userRouter.post("/signup", async (req, res) => {

const hashedPassword = await bcryptjs.hash(password, 8);
const newUser = new User({
firstName,
lastName,
username,
email,
password: hashedPassword,
Expand All @@ -57,11 +56,11 @@ userRouter.post("/signup", async (req, res) => {

userRouter.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
let { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ msg: "Please fill in all fields" });
}

email = email.toLowerCase();
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ msg: "User with this email does not exist" });
Expand All @@ -78,11 +77,9 @@ userRouter.post("/login", async (req, res) => {
user: {
username: user.username,
id: user._id,
lastName: user.lastName,
email: user.email,
gamesPlayed: user.gamesPlayed,
totalScore: user.totalScore,
firstName: user.firstName,
//pastGameData: user.pastGameData,
},
});
Expand Down Expand Up @@ -112,8 +109,6 @@ userRouter.get("/", auth, async (req, res) => {
res.json({
username: user.username,
id: user._id,
lastName: user.lastName,
firstName: user.firstName,
email: user.email,
gamesPlayed: user.gamesPlayed,
totalScore: user.totalScore,
Expand All @@ -127,8 +122,6 @@ userRouter.get("/pastGameData", auth, async (req, res) => {
res.json({
// username: user.username,
// id: user._id,
// lastName: user.lastName,
// firstName: user.firstName,
// email: user.email,
gamesPlayed: user.gamesPlayed,
totalScore: user.totalScore,
Expand Down
9 changes: 6 additions & 3 deletions packages/backend/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ const User = require("./models/User");
const leaderboard = require("./routes/api/leaderboards");
const Leaderboards = require("./models/Leaderboard");
const users = require("./routes/api/users");
const cron = require("node-cron");
dotenv.config();

const app = express();
Expand All @@ -25,8 +26,11 @@ mongoose
.connect(URI)
.then(() => {
console.log("Mongo Connection Suceeded...");
deleteOldGames();
findTopUsers();

cron.schedule("*/15 * * * *", function () {
deleteOldGames();
findTopUsers();
});
})
.catch((err) => {
console.log(`Error in DB Connection ${err}`);
Expand Down Expand Up @@ -66,7 +70,6 @@ async function findTopUsers() {
newArray.push({ username: x.username, gamesPlayed: x.gamesPlayed, totalScore: x.totalScore });
});
const newLeaderboard = await Leaderboards.create({ topUsers: newArray });
if (newLeaderboard) console.log("Updated leaderboard");
} catch (error) {
console.log(error.message);
}
Expand Down
1 change: 1 addition & 0 deletions packages/uga-geoguessr/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/uga-geoguessr/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ function App() {
localStorage.setItem("auth-token", "");
token = "";
}
const tokenResponse = await axios.post("http://localhost:4000/api/users/tokenIsValid", null, {
const tokenResponse = await axios.post(`${process.env.REACT_APP_BACKEND}/api/users/tokenIsValid`, null, {
headers: { "x-auth-token": token },
});
if (!tokenResponse) throw new Error("Couldnt not validate login");
if (tokenResponse.data) {
const userRes = await axios.get("http://localhost:4000/api/users/", {
const userRes = await axios.get(`${process.env.REACT_APP_BACKEND}/api/users/`, {
headers: { "x-auth-token": token },
});
setUserData({ token, user: userRes.data });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ const GoogleMapWindow: React.FC<Props> = ({
}
: {};
const response = await axios.put(
`http://localhost:4000/api/games/${_id}`,
`${process.env.REACT_APP_BACKEND}/api/games/${_id}`,
{
nextStage,
...newthing,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const ResultsWindow: React.FC<Props> = ({ setCurrentStageNumber, nextStage, show
},
};
const response = await axios.post(
`http://localhost:4000/api/games`,
`${process.env.REACT_APP_BACKEND}/api/games`,
{
gameType: { _id: data.gameTypeId, title: data.gameTypeTitle },
numberOfStages: data.numberOfStages,
Expand Down
2 changes: 1 addition & 1 deletion packages/uga-geoguessr/src/components/GameType/Card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const Card: React.FC<Props> = ({ gameType, setModalData, fetchData }) => {
async function handleDeleteRequest() {
try {
let token = localStorage.getItem("auth-token");
const response = await axios.delete(`http://localhost:4000/api/gametypes/${gameType._id}/`, {
const response = await axios.delete(`${process.env.REACT_APP_BACKEND}/api/gametypes/${gameType._id}/`, {
headers: {
"Content-Type": "application/json",
"x-auth-token": token,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const PlayGameTypeModal: React.FC<Props> = ({ gameType, setModalData }) => {
},
};
const response = await axios.post(
`http://localhost:4000/api/games`,
`${process.env.REACT_APP_BACKEND}/api/games`,
{
gameType: gameType,
numberOfStages: numberOfStages,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,35 @@ const NewGameType: React.FC<NewGameProps> = ({ onAddGame, editGameType }) => {
</button>
<div className="font-bold">Selected Locations:</div>
<div className="grid grid-cols-3 text-center">
<h2 className="font-bold text-xl break-words ">Lat</h2>
<h2
// onClick={(e) => {
// let stringl = "";
// locations.forEach((loc) => {
// let thing = `{ lat: ${loc.lat}, lng: ${loc.lng}, radius: ${Math.trunc(
// loc.radius,
// )}},`;
// stringl += thing;
// });
// navigator.clipboard.writeText(stringl);
// console.log(stringl);
// }}
className="font-bold text-xl break-words "
>
Lat
</h2>
<h2 className="font-bold text-xl break-words ">Lng</h2>
<h2 className="font-bold text-xl break-words">Radius (meters)</h2>
{locations.map((current, index) => {
const oddoreven = index % 2 !== 0;
return (
<>
<h2
// onClick={(e) => {
// let thing = `{ lat: ${current.lat}, lng: ${
// current.lng
// }, radius: ${Math.trunc(current.radius)}},`;
// navigator.clipboard.writeText(thing);
// }}
className={` ${
oddoreven ? "" : classes.light_background
} font-bold text-xl break-words w-full text-left pl-4`}
Expand Down
2 changes: 1 addition & 1 deletion packages/uga-geoguessr/src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function Header() {
},

{
name: "Available Games",
name: "Play Game",
href: "/AvailableGames",
},
];
Expand Down
Loading