4 Commits

26 changed files with 407 additions and 386 deletions

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

8
.idea/ScoreSpot.iml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="CPP_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/copilot.data.migration.agent.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AgentMigrationStateService">
<option name="migrationStatus" value="COMPLETED" />
</component>
</project>

6
.idea/copilot.data.migration.ask.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AskMigrationStateService">
<option name="migrationStatus" value="COMPLETED" />
</component>
</project>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Ask2AgentMigrationStateService">
<option name="migrationStatus" value="COMPLETED" />
</component>
</project>

6
.idea/copilot.data.migration.edit.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EditMigrationStateService">
<option name="migrationStatus" value="COMPLETED" />
</component>
</project>

8
.idea/icon.svg generated Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 10 KiB

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ScoreSpot.iml" filepath="$PROJECT_DIR$/.idea/ScoreSpot.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

View File

@@ -56,7 +56,7 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
**Once the following dependencies above are installed navigate to the top of the repsoitory and copy the following link:**
> <https://github.com/LucasPatenaude/ScoreSpot.git>
> <https://gitlab.com/lucaspatenaude/ScoreSpot.git>
**Using a Git GUI or the terminal select a location to store the repository. In this example, I'll store it in a folder called `programming` in the home directory**
@@ -88,8 +88,7 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
`git clone https://github.com/LucasPatenaude/ScoreSpot.git`
> 💡 TIP 💡
>
> [!IMPORTANT]
> Congragulations! ScoreSpot should now be cloned into `~/programming`
---
@@ -116,8 +115,7 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
`docker-compose up -d`
> 💡 TIP 💡
>
> [!IMPORTANT]
> Congragulations! ScoreSpot should now be deployed on your server at port 3000
>
> To enter your ScoreSpot deployment enter `localhost:3000/` into your browser's addess bar
@@ -166,8 +164,7 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
}
```
> 💡 TIP 💡
>
> [!IMPORTANT]
> Congragulations! ScoreSpot should now show it's test results on bootup
>
> To view the test results navigate to Docker and open the container's logs

View File

@@ -12,7 +12,7 @@ services:
- "5432:5432"
volumes:
- users-database:/var/lib/postgresql/data
- ./src/database/init_data:/docker-entrypoint-initdb.d
- src/init_data:/docker-entrypoint-initdb.d
web:
container_name: node-web-interface
image: node:lts

View File

@@ -1,71 +1,71 @@
/* Standardized Styling for Login, Registration, and Account Panes */
.account-portal-container {
width: 400px;
position: absolute;
top: 150px; /* Adjust this value as needed */
right: 20px; /* Adjust this value as needed */
z-index: 5;
background: linear-gradient(
to bottom,
white,
rgb(245, 245, 245),
rgb(227, 227, 227)
); /* Gradient from white to gray */
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.5);
border: 1px solid gray;
width: 400px;
position: absolute;
top: 150px; /* Adjust this value as needed */
right: 20px; /* Adjust this value as needed */
z-index: 5;
background: linear-gradient(to bottom, white, rgb(245, 245, 245), rgb(227, 227, 227)); /* Gradient from white to gray */
box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.5);
border: 1px solid gray;
}
/* Set Login and Registration Panes to be same size */
#login-pane,
#register-pane {
height: 408px;
#login-pane, #register-pane {
height: 408px;
}
/* */
.form-container {
width: 70%; /* Adjust width as needed */
margin: 0 auto; /* Center horizontally */
text-align: center; /* Center text horizontally */
width: 70%; /* Adjust width as needed */
margin: 0 auto; /* Center horizontally */
text-align: center; /* Center text horizontally */
}
.account-portal-button {
text-decoration: none;
text-decoration: none;
padding: 5px 10px;
background-color: red;
border-color: red;
padding: 5px 10px;
background-color: red;
border-color: red;
border: 1px solid red;
border-radius: 8px;
color: white;
border: 1px solid red;
border-radius: 8px;
color: white;
}
.account-portal-button:hover {
background-color: darkred;
border-color: darkred;
color: white;
background-color: darkred;
border-color: darkred;
color: white;
}
body {
font-family: "Golos Text";
}
/* Apply modern styling to inputs and select elements */
#form-control,
select {
width: 70%; /* Make inputs and select elements same width */
padding: 0.375rem 0.75rem; /* Example padding */
font-size: 1rem; /* Example font size */
line-height: 1.5; /* Example line height */
color: #495057; /* Example text color */
background-color: #fff; /* Example background color */
border: 1px solid #ced4da; /* Example border */
border-radius: 0.25rem; /* Example border radius */
margin-bottom: 10px; /* Example margin */
width: 70%; /* Make inputs and select elements same width */
padding: 0.375rem 0.75rem; /* Example padding */
font-size: 1rem; /* Example font size */
line-height: 1.5; /* Example line height */
color: #495057; /* Example text color */
background-color: #fff; /* Example background color */
border: 1px solid #ced4da; /* Example border */
border-radius: 0.25rem; /* Example border radius */
margin-bottom: 10px; /* Example margin */
}
/* Adjust styling for form labels */
.form-label {
font-weight: bold; /* Example font weight */
font-weight: bold; /* Example font weight */
}
/* Adjust styling for buttons */
.btn {
margin-top: 30px; /* Example margin */
margin-top: 30px; /* Example margin */
}

View File

@@ -75,9 +75,9 @@
{{#each topScorers.scorers}}
<tr id="top-scorers-row">
<td id="league-top-scorers-goals-column">{{goals}}</td>
<td><img id="league-top-scorers-logo" href="/club/{{team.team_id}}" src="{{team.team_crest}}" alt="{{table.team_name}} Crest"></img></td>
<td><img id="league-top-scorers-logo" clubID="{{team.team_id}}" src="{{team.team_crest}}" alt="{{table.team_name}} Crest"></img></td>
<td id="league-top-scorers-player-name-column">{{player.player_name}}</td>
<td id="league-top-scorers-club-name-column" href="/club/{{team.team_id}}">{{team.team_name}}</td>
<td id="league-top-scorers-club-name-column" clubID="{{team.team_id}}">{{team.team_name}}</td>
<td>{{games_played}}</td>
</tr>
{{/each}}

View File

@@ -13,11 +13,11 @@
></script>
<!-- Homepage Scripts -->
<script src="/src/routes/league-pages/redirect-to-league-url.js"></script>
<script src="/routes/league-pages/redirect-to-league-url.js"></script>
<!-- League Pages Scripts -->
<script src="/js/league-page/change-goal-difference-color.js"></script>
<script src="/src/routes/club-pages/redirect-to-club-url.js"></script>
<script src="/routes/club-pages/redirect-to-club-url.js"></script>
<!-- Club Pages Scripts -->
<script src="/js/club-page/favorite-button.js"></script>

View File

@@ -4,7 +4,7 @@
<!-- Set the Content-Security-Policy header to allow inline scripts -->
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' https://code.jquery.com https://cdn.jsdelivr.net https://stackpath.bootstrapcdn.com;">
<title>ScoreSpot</title>
<title>Group 6 Final Project</title>
<!--------------- CSS Stylesheets ---------------->

View File

@@ -13,37 +13,69 @@ const bcrypt = require("bcryptjs"); // To hash passwords
const axios = require("axios"); // To make HTTP requests from our server. We'll learn more about it in Part C.
const moment = require("moment"); // To extract current time data
// Start the Database
const db = require("../config/database"); // Import the db module
// Export the app object to index.js
module.exports = app;
// *****************************************************
// <!-- Section 2 : Connect to DB -->
// *****************************************************
// Start the Database
const db = require("./database/db"); // Import the db module
// create `ExpressHandlebars` instance and configure the layouts and partials dir.
const hbs = handlebars.create({
extname: "hbs",
layoutsDir: __dirname + "/../public/views/layouts",
partialsDir: __dirname + "/../public/views/partials",
});
// *****************************************************
// <!-- Section 3 : Handlebars COnfiguration -->
// <!-- Section 3 : App Settings -->
// *****************************************************
// express-handlebars is a Handlebars view engine for Express. Handlebars.js is a popular templating engine that is powerful, flexible, and helps to create reusable HTML templates.
const hbs = require("./config/handlebars"); // Import the hbs module
// Register `hbs` as our view engine using its bound `engine()` function.
app.engine("hbs", hbs.engine);
app.set("view engine", "hbs");
app.set("views", path.join(__dirname, "../public/views"));
app.use(express.static(path.join(__dirname, "../public/assets"))); // Serve asset files from the 'public/assets' directory
app.set("views", path.join(__dirname, "/../public/views"));
app.use(bodyParser.json()); // specify the usage of JSON for parsing request body.
// *****************************************************
// <!-- Section 4 : Session Setup -->
// *****************************************************
// initialize session variables
app.get("/welcome", (req, res) => {
res.json({ status: "success", message: "Welcome!" });
});
app.use(
session({
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
})
);
const sessionConfig = require("./config/session"); // Import the hbs module
sessionConfig(app);
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(async function (req, res, next) {
res.locals.user = req.session.user;
// *****************************************************
// <!-- Section 5 : Website Routes -->
// *****************************************************
if (res.locals.user) {
try {
res.locals.fav_teams = await getFavoriteTeamsForUser(
res.locals.user.userid
);
} catch (error) {
console.error("Error fetching favorite teams:", error);
}
}
next();
});
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, "/../public/assets")));
app.use(express.static(path.join(__dirname, "/")));
// *****************************************************
// <!-- Section 4 : Middleware -->
@@ -58,9 +90,23 @@ app.use(fetchMatchesData);
const convert_time = require("./middleware/navigation-bar/convert-time");
app.use(convert_time);
// Other middleware and route imports
const leagueRoutes = require("./routes/league-pages/league-routes");
leagueRoutes(app);
// Leagues Page Middleware
const fetchLeaguesData = require("./middleware/leagues-page/get-current-league-information");
const fetchLeagueScorerData = require("./middleware/leagues-page/get-current-league-top-scorers");
app.get(
"/league/:leagueID",
[fetchLeaguesData, fetchLeagueScorerData],
(req, res) => {
// Render the Handlebars view with league data
res.render("pages/leagues-page", {
leagueID: req.params.leagueID,
leagues: res.locals.leagues,
scorers: res.locals.topScorers, // Assuming fetchLeagueScorerData sets the data in res.locals.scorers
});
}
);
// Clubs Page Middleware
@@ -91,73 +137,246 @@ app.get("/club/:clubID", [fetchClubsData], (req, res) => {
});
// *****************************************************
// <!-- Section 5 : Routes -->
// <!-- Section 5 : API Routes -->
// *****************************************************
/************************
Home Page Routes
*************************/
// ************************
// Login Page Routes
// *************************
// Redirect to the home page
// Redirect to the /login endpoint
app.get("/", (req, res) => {
res.redirect("/home");
});
// Render the home page
// Render login page for /login route
app.get("/login", (req, res) => {
res.render("/");
});
// Trigger login form to check database for matching username and password
app.post("/login", async (req, res) => {
try {
// Check if username exists in DB
const user = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
if (!user) {
// Redirect user to login screen if no user is found with the provided username
return res.redirect("/register");
}
// Check if password from request matches with password in DB
const match = await bcrypt.compare(req.body.password, user.password);
// Check if match returns no data
if (!match) {
// Render the login page with the message parameter
return res.render("/", { message: "Password does not match" });
} else {
// Save user information in the session variable
req.session.user = user;
req.session.save();
// Redirect user to the home page
res.redirect("/");
}
} catch (error) {
// Direct user to login screen if no user is found with matching password
res.redirect("/register");
}
});
// **************************
// Registration Page Routes
// **************************
// Render registration page for /register route
app.get("/register", (req, res) => {
res.redirect("/");
});
// Trigger Registration Form to Post
app.post("/register", async (req, res) => {
try {
if (!req.body.username || !req.body.password) {
// If username or password is missing, respond with status 400 and an error message
return res
.status(400)
.json({ status: "error", message: "Invalid input" });
}
// Check if the username already exists in the database
const existingUser = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
if (existingUser) {
// If a user with the same username already exists, respond with status 409 and an error message
return res
.status(409)
.json({ status: "error", message: "Username already exists" });
}
// Hash the password using bcrypt library
const hash = await bcrypt.hash(req.body.password, 10);
// Insert username and hashed password into the 'users' table
await db.none("INSERT INTO users (username, password) VALUES ($1, $2)", [
req.body.username,
hash,
]);
const user = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
req.session.user = user;
req.session.save();
// Redirect user to the home page
res.redirect("/home");
} catch (error) {
// If an error occurs during registration, respond with status 500 and an error message
res.status(500).json({
status: "error",
message: "An error occurred during registration",
});
}
});
// *************************
// Home Page Routes
// *************************
app.get("/home", (req, res) => {
const loggedIn = req.session.user ? true : false;
res.render("pages/home");
});
/************************
Login Page Routes
*************************/
app.get("/logout", (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error("Error destroying session:", err);
res.status(500).send("Internal Server Error");
} else {
// Redirect to the same page after destroying the session
res.redirect("/"); // You can change '/' to the desired page if it's not the home page
}
});
});
// Account Routes
const loginRoutes = require("./routes/account/login");
app.use("/", loginRoutes);
/************************
Registration Page Routes
*************************/
// Account Routes
const registerRoutes = require("./routes/account/register");
app.use("/", registerRoutes);
/************************
Logout Route
*************************/
const logoutRoute = require("./routes/account/logout");
app.use("/", logoutRoute);
/************************
League Page Routes
*************************/
// *************************
// League Page Routes
// *************************
// Import and call generateLeagueRoutes function
const generateLeagueRoutes = require("./routes/league-pages/generate-league-routes");
generateLeagueRoutes(app);
/************************
Club Page Routes
*************************/
// *************************
// Club Page Routes
// *************************
// Import and call generateLeagueRoutes function
const generateClubRoutes = require("./routes/club-pages/generate-club-routes");
generateClubRoutes(app);
/************************
Favorite Team Database
*************************/
// *************************
// Favorite Team Database
// *************************
const databaseRoutes = require("./routes/database/database-routes").router;
app.use("/", databaseRoutes);
// Function to add a new row to the FavoriteTeams table
// database configuration
// *****************************************************
// <!-- Section 6 : Export the App Module to Index.js -->
// *****************************************************
app.post("/favteam/add", async (req, res, next) => {
try {
const { userID, teamID, teamName, teamLogo } = req.body;
// Export the app object to index.js
module.exports = app;
// Check if the user is logged in
if (!req.session.user) {
return res
.status(400)
.json({ message: "Login or register to add a favorite team." });
}
// Insert the new favorite team into the database
const query = {
text: "INSERT INTO FavoriteTeams (UserID, TeamID, TeamName, TeamLogo) VALUES ($1, $2, $3, $4)",
values: [userID, teamID, teamName, teamLogo],
};
await db.none(query);
console.log("New favorite team added successfully.");
return res
.status(200)
.json({ message: "New favorite team added successfully." });
} catch (error) {
console.error("Error adding favorite team:", error);
return res.status(500).json({ error: "Error adding favorite team" });
}
});
app.post("/favteam/remove", async (req, res) => {
try {
const { userID, teamID } = req.body;
// Check if the team exists for the user
const existingTeam = await db.oneOrNone(
"SELECT * FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2",
[userID, teamID]
);
// If the team does not exist for the user, return a 404 error
if (!existingTeam) {
return res
.status(404)
.json({ message: "This team is not in your favorites." });
}
// Remove the favorite team from the database
await db.none(
"DELETE FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2",
[userID, teamID]
);
console.log("Favorite team removed successfully.");
return res
.status(200)
.json({ message: "Favorite team removed successfully." });
} catch (error) {
console.error("Error removing favorite team:", error);
// If the error is a database error, return a 500 error
if (error instanceof QueryResultError) {
return res.status(500).json({
error: "Database error occurred while removing favorite team",
});
}
// If the error is a generic error, return a 400 error
return res
.status(400)
.json({ error: "Error occurred while removing favorite team" });
}
});
async function getFavoriteTeamsForUser(userId) {
try {
// Execute the SQL query
const favoriteTeams = await db.any(
`
SELECT * FROM FavoriteTeams
WHERE UserID = $1;
`,
userId
);
`a`;
// Return the result
return favoriteTeams;
} catch (error) {
console.error("Error fetching favorite teams:", error);
throw error; // Rethrow the error for handling at a higher level
}
}

View File

@@ -1,8 +0,0 @@
// create `ExpressHandlebars` instance and configure the layouts and partials dir.
const expressHandlebars = require("express-handlebars"); // express-handlebars is a Handlebars view engine for Express. Handlebars.js is a popular templating engine that is powerful, flexible, and helps to create reusable HTML templates.
const hbs = expressHandlebars.create({
extname: "hbs",
layoutsDir: __dirname + "./../../public/views/layouts",
partialsDir: __dirname + "./../../public/views/partials",
});
module.exports = hbs;

View File

@@ -1,39 +0,0 @@
const session = require("express-session"); // express-session is a middleware for Express that enables session management. It allows you to store user data between HTTP requests.
const bodyParser = require("body-parser"); // body-parser is a middleware that parses incoming request bodies in a middleware before your handlers. It's used to extract the entire body portion of an incoming request stream and exposes it on req.body.
const databaseRoutes = require("../routes/database/database-routes");
const getFavoriteTeamsForUser =
require("../routes/database/database-routes").getFavoriteTeamsForUser;
const sessionConfig = (app) => {
app.use(
session({
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
})
);
app.use(
bodyParser.urlencoded({
extended: true,
})
);
// Check if user has any favorite teams in database
app.use(async function (req, res, next) {
res.locals.user = req.session.user;
if (res.locals.user) {
try {
res.locals.fav_teams = await getFavoriteTeamsForUser(
res.locals.user.userid
);
} catch (error) {
console.error("Error fetching favorite teams:", error);
}
}
next();
});
};
module.exports = sessionConfig;

View File

@@ -1,16 +0,0 @@
const express = require("express");
const router = express.Router();
router.get("/logout", (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error("Error destroying session:", err);
res.status(500).send("Internal Server Error");
} else {
// Redirect to the same page after destroying the session
res.redirect("/"); // You can change '/' to the desired page if it's not the home page
}
});
});
module.exports = router;

View File

@@ -1,53 +0,0 @@
const express = require("express");
const db = require("../../database/db"); // Import the db modulei
const bcrypt = require("bcryptjs"); // To hash passwords
const router = express.Router();
// Trigger Registration Form to Post
router.post("/register", async (req, res) => {
try {
if (!req.body.username || !req.body.password) {
// If username or password is missing, respond with status 400 and an error message
return res
.status(400)
.json({ status: "error", message: "Invalid input" });
}
// Check if the username already exists in the database
const existingUser = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
if (existingUser) {
// If a user with the same username already exists, respond with status 409 and an error message
return res
.status(409)
.json({ status: "error", message: "Username already exists" });
}
// Hash the password using bcrypt library
const hash = await bcrypt.hash(req.body.password, 10);
// Insert username and hashed password into the 'users' table
await db.none("INSERT INTO users (username, password) VALUES ($1, $2)", [
req.body.username,
hash,
]);
const user = await db.oneOrNone(
"SELECT * FROM users WHERE username = $1",
req.body.username
);
req.session.user = user;
req.session.save();
// Redirect user to the home page
res.redirect("/");
} catch (error) {
// If an error occurs during registration, respond with status 500 and an error message
res.status(500).json({
status: "error",
message: "An error occurred during registration",
});
}
});
module.exports = router;

View File

@@ -1,99 +0,0 @@
const express = require("express");
const db = require("../../database/db");
const router = express.Router();
// Function to add a new row to the FavoriteTeams table
// database configuration
router.post("/favteam/add", async (req, res, next) => {
try {
const { userID, teamID, teamName, teamLogo } = req.body;
// Check if the user is logged in
if (!req.session.user) {
return res
.status(400)
.json({ message: "Login or register to add a favorite team." });
}
// Insert the new favorite team into the database
const query = {
text: "INSERT INTO FavoriteTeams (UserID, TeamID, TeamName, TeamLogo) VALUES ($1, $2, $3, $4)",
values: [userID, teamID, teamName, teamLogo],
};
await db.none(query);
console.log("New favorite team added successfully.");
return res
.status(200)
.json({ message: "New favorite team added successfully." });
} catch (error) {
console.error("Error adding favorite team:", error);
return res.status(500).json({ error: "Error adding favorite team" });
}
});
router.post("/favteam/remove", async (req, res) => {
try {
const { userID, teamID } = req.body;
// Check if the team exists for the user
const existingTeam = await db.oneOrNone(
"SELECT * FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2",
[userID, teamID]
);
// If the team does not exist for the user, return a 404 error
if (!existingTeam) {
return res
.status(404)
.json({ message: "This team is not in your favorites." });
}
// Remove the favorite team from the database
await db.none(
"DELETE FROM FavoriteTeams WHERE UserID = $1 AND TeamID = $2",
[userID, teamID]
);
console.log("Favorite team removed successfully.");
return res
.status(200)
.json({ message: "Favorite team removed successfully." });
} catch (error) {
console.error("Error removing favorite team:", error);
// If the error is a database error, return a 500 error
if (error instanceof QueryResultError) {
return res.status(500).json({
error: "Database error occurred while removing favorite team",
});
}
// If the error is a generic error, return a 400 error
return res
.status(400)
.json({ error: "Error occurred while removing favorite team" });
}
});
async function getFavoriteTeamsForUser(userId) {
try {
// Execute the SQL query
const favoriteTeams = await db.any(
`
SELECT * FROM FavoriteTeams
WHERE UserID = $1;
`,
userId
);
`a`;
// Return the result
return favoriteTeams;
} catch (error) {
console.error("Error fetching favorite teams:", error);
throw error; // Rethrow the error for handling at a higher level
}
}
module.exports = { router, getFavoriteTeamsForUser };

View File

@@ -1,25 +0,0 @@
// src/routes/leagueRoutes.js
const express = require("express");
const app = express();
// Import the middleware functions
const fetchLeaguesData = require("../../middleware/leagues-page/get-current-league-information");
const fetchLeagueScorerData = require("../../middleware/leagues-page/get-current-league-top-scorers");
// Define the route handling function
const leagueRoutes = (app) => {
app.get(
"/league/:leagueID",
[fetchLeaguesData, fetchLeagueScorerData],
(req, res) => {
// Render the Handlebars view with league data
res.render("pages/leagues-page", {
leagueID: req.params.leagueID,
leagues: res.locals.leagues,
scorers: res.locals.topScorers, // Assuming fetchLeagueScorerData sets the data in res.locals.scorers
});
}
);
};
module.exports = leagueRoutes;

View File

@@ -1,15 +1,20 @@
const express = require("express");
const db = require("../../database/db"); // Import the db module
const bcrypt = require("bcryptjs"); // To hash passwords
const router = express.Router();
const bcrypt = require("bcryptjs");
const db = require("../config/database");
// Redirect to the /login endpoint
app.get("/", (req, res) => {
res.redirect("/home");
});
// Render login page for /login route
router.get("/login", (req, res) => {
res.redirect("/");
app.get("/login", (req, res) => {
res.render("/");
});
// Trigger login form to check database for matching username and password
router.post("/login", async (req, res) => {
app.post("/login", async (req, res) => {
try {
// Check if username exists in DB
const user = await db.oneOrNone(
@@ -19,7 +24,7 @@ router.post("/login", async (req, res) => {
if (!user) {
// Redirect user to login screen if no user is found with the provided username
return res.render("pages/home", { message: "User Not Found!" });
return res.redirect("/register");
}
// Check if password from request matches with password in DB
@@ -28,7 +33,7 @@ router.post("/login", async (req, res) => {
// Check if match returns no data
if (!match) {
// Render the login page with the message parameter
return res.render("pages/home", { message: "Password does not match" });
return res.render("/", { message: "Password does not match" });
} else {
// Save user information in the session variable
req.session.user = user;
@@ -43,4 +48,4 @@ router.post("/login", async (req, res) => {
}
});
module.exports = router;
module.exports = loginRoutes;

View File

@@ -1,22 +0,0 @@
const express = require("express");
const app = express();
const session = require("express-session");
// Set up session middleware
app.use(
session({
secret: "your secret key",
resave: false,
saveUninitialized: true,
})
);
// Other middleware and setup code...
// Import routes
require("./app.js")(app);
// Start the server
app.listen(3000, () => {
console.log("Server is running on port 3000");
});