Compare commits
12 Commits
main
...
split-appj
| Author | SHA1 | Date | |
|---|---|---|---|
| e7d27986c6 | |||
| 1f5c1dc693 | |||
| fe73a1dcb4 | |||
| 3e7f80232f | |||
| 60e5c54ebe | |||
| 1b106f4385 | |||
| 32fc1ff745 | |||
| b8e4fa5473 | |||
| 322a7c6f20 | |||
| a3ec0ca01d | |||
| ebb558542c | |||
| b2ec54daf8 |
@@ -12,7 +12,7 @@ services:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- users-database:/var/lib/postgresql/data
|
||||
- src/init_data:/docker-entrypoint-initdb.d
|
||||
- ./src/database/init_data:/docker-entrypoint-initdb.d
|
||||
web:
|
||||
container_name: node-web-interface
|
||||
image: node:lts
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
/* Standardized Styling for Login, Registration, and Account Panes */
|
||||
.account-portal-container {
|
||||
width: 400px;
|
||||
@@ -6,13 +5,19 @@
|
||||
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 */
|
||||
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 {
|
||||
#login-pane,
|
||||
#register-pane {
|
||||
height: 408px;
|
||||
}
|
||||
|
||||
@@ -41,10 +46,6 @@
|
||||
color: white;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Golos Text";
|
||||
}
|
||||
|
||||
/* Apply modern styling to inputs and select elements */
|
||||
#form-control,
|
||||
select {
|
||||
@@ -68,4 +69,3 @@ select {
|
||||
.btn {
|
||||
margin-top: 30px; /* Example margin */
|
||||
}
|
||||
|
||||
|
||||
@@ -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" clubID="{{team.team_id}}" src="{{team.team_crest}}" alt="{{table.team_name}} Crest"></img></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 id="league-top-scorers-player-name-column">{{player.player_name}}</td>
|
||||
<td id="league-top-scorers-club-name-column" clubID="{{team.team_id}}">{{team.team_name}}</td>
|
||||
<td id="league-top-scorers-club-name-column" href="/club/{{team.team_id}}">{{team.team_name}}</td>
|
||||
<td>{{games_played}}</td>
|
||||
</tr>
|
||||
{{/each}}
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
></script>
|
||||
|
||||
<!-- Homepage Scripts -->
|
||||
<script src="/routes/league-pages/redirect-to-league-url.js"></script>
|
||||
<script src="/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="/routes/club-pages/redirect-to-club-url.js"></script>
|
||||
<script src="/src/routes/club-pages/redirect-to-club-url.js"></script>
|
||||
|
||||
<!-- Club Pages Scripts -->
|
||||
<script src="/js/club-page/favorite-button.js"></script>
|
||||
|
||||
@@ -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>Group 6 Final Project</title>
|
||||
<title>ScoreSpot</title>
|
||||
|
||||
<!--------------- CSS Stylesheets ---------------->
|
||||
|
||||
|
||||
329
src/app.js
329
src/app.js
@@ -13,69 +13,37 @@ 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 -->
|
||||
// *****************************************************
|
||||
|
||||
// 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",
|
||||
});
|
||||
// Start the Database
|
||||
const db = require("./database/db"); // Import the db module
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 3 : App Settings -->
|
||||
// <!-- Section 3 : Handlebars COnfiguration -->
|
||||
// *****************************************************
|
||||
|
||||
// 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.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.use(bodyParser.json()); // specify the usage of JSON for parsing request body.
|
||||
|
||||
// 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,
|
||||
})
|
||||
);
|
||||
// *****************************************************
|
||||
// <!-- Section 4 : Session Setup -->
|
||||
// *****************************************************
|
||||
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
extended: true,
|
||||
})
|
||||
);
|
||||
app.use(async function (req, res, next) {
|
||||
res.locals.user = req.session.user;
|
||||
const sessionConfig = require("./config/session"); // Import the hbs module
|
||||
sessionConfig(app);
|
||||
|
||||
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 5 : Website Routes -->
|
||||
// *****************************************************
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 4 : Middleware -->
|
||||
@@ -90,23 +58,9 @@ app.use(fetchMatchesData);
|
||||
const convert_time = require("./middleware/navigation-bar/convert-time");
|
||||
app.use(convert_time);
|
||||
|
||||
// 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
|
||||
});
|
||||
}
|
||||
);
|
||||
// Other middleware and route imports
|
||||
const leagueRoutes = require("./routes/league-pages/league-routes");
|
||||
leagueRoutes(app);
|
||||
|
||||
// Clubs Page Middleware
|
||||
|
||||
@@ -137,134 +91,46 @@ app.get("/club/:clubID", [fetchClubsData], (req, res) => {
|
||||
});
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 5 : API Routes -->
|
||||
// <!-- Section 5 : Routes -->
|
||||
// *****************************************************
|
||||
|
||||
/************************
|
||||
Login Page Routes
|
||||
*************************/
|
||||
|
||||
// Redirect to the /login endpoint
|
||||
app.get("/", (req, res) => {
|
||||
res.redirect("/home");
|
||||
});
|
||||
|
||||
// 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
|
||||
*************************/
|
||||
|
||||
// Redirect to the home page
|
||||
app.get("/", (req, res) => {
|
||||
res.redirect("/home");
|
||||
});
|
||||
|
||||
// Render the home page
|
||||
app.get("/home", (req, res) => {
|
||||
const loggedIn = req.session.user ? true : false;
|
||||
res.render("pages/home");
|
||||
});
|
||||
|
||||
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
|
||||
}
|
||||
});
|
||||
});
|
||||
/************************
|
||||
Login Page Routes
|
||||
*************************/
|
||||
|
||||
// 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
|
||||
@@ -286,97 +152,12 @@ generateClubRoutes(app);
|
||||
Favorite Team Database
|
||||
*************************/
|
||||
|
||||
// Function to add a new row to the FavoriteTeams table
|
||||
// database configuration
|
||||
const databaseRoutes = require("./routes/database/database-routes").router;
|
||||
app.use("/", databaseRoutes);
|
||||
|
||||
app.post("/favteam/add", async (req, res, next) => {
|
||||
try {
|
||||
const { userID, teamID, teamName, teamLogo } = req.body;
|
||||
// *****************************************************
|
||||
// <!-- Section 6 : Export the App Module to Index.js -->
|
||||
// *****************************************************
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
// Export the app object to index.js
|
||||
module.exports = app;
|
||||
|
||||
8
src/config/handlebars.js
Normal file
8
src/config/handlebars.js
Normal file
@@ -0,0 +1,8 @@
|
||||
// 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;
|
||||
39
src/config/session.js
Normal file
39
src/config/session.js
Normal file
@@ -0,0 +1,39 @@
|
||||
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;
|
||||
@@ -1,20 +1,15 @@
|
||||
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
|
||||
app.get("/login", (req, res) => {
|
||||
res.render("/");
|
||||
router.get("/login", (req, res) => {
|
||||
res.redirect("/");
|
||||
});
|
||||
|
||||
// Trigger login form to check database for matching username and password
|
||||
app.post("/login", async (req, res) => {
|
||||
router.post("/login", async (req, res) => {
|
||||
try {
|
||||
// Check if username exists in DB
|
||||
const user = await db.oneOrNone(
|
||||
@@ -24,7 +19,7 @@ app.post("/login", async (req, res) => {
|
||||
|
||||
if (!user) {
|
||||
// Redirect user to login screen if no user is found with the provided username
|
||||
return res.redirect("/register");
|
||||
return res.render("pages/home", { message: "User Not Found!" });
|
||||
}
|
||||
|
||||
// Check if password from request matches with password in DB
|
||||
@@ -33,7 +28,7 @@ app.post("/login", async (req, res) => {
|
||||
// Check if match returns no data
|
||||
if (!match) {
|
||||
// Render the login page with the message parameter
|
||||
return res.render("/", { message: "Password does not match" });
|
||||
return res.render("pages/home", { message: "Password does not match" });
|
||||
} else {
|
||||
// Save user information in the session variable
|
||||
req.session.user = user;
|
||||
@@ -48,4 +43,4 @@ app.post("/login", async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = loginRoutes;
|
||||
module.exports = router;
|
||||
16
src/routes/account/logout.js
Normal file
16
src/routes/account/logout.js
Normal file
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
53
src/routes/account/register.js
Normal file
53
src/routes/account/register.js
Normal file
@@ -0,0 +1,53 @@
|
||||
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;
|
||||
99
src/routes/database/database-routes.js
Normal file
99
src/routes/database/database-routes.js
Normal file
@@ -0,0 +1,99 @@
|
||||
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 };
|
||||
25
src/routes/league-pages/league-routes.js
Normal file
25
src/routes/league-pages/league-routes.js
Normal file
@@ -0,0 +1,25 @@
|
||||
// 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;
|
||||
22
src/server.js
Normal file
22
src/server.js
Normal file
@@ -0,0 +1,22 @@
|
||||
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");
|
||||
});
|
||||
Reference in New Issue
Block a user