Fixes to file structure
@@ -3,9 +3,6 @@
|
||||
"dockerComposeFile": "../docker-compose.yml",
|
||||
"service": "web",
|
||||
"workspaceFolder": "/home/node/app",
|
||||
"extensions": [
|
||||
"ecmel.vscode-html-css"
|
||||
],
|
||||
"forwardPorts": [3000],
|
||||
"postCreateCommand": "npm install"
|
||||
}
|
||||
19
README.md
@@ -1,4 +1,4 @@
|
||||
<img src="src/assets/img/logo.png" width="80%"/>
|
||||
<img src="public/assets/img/logo.png" width="80%">
|
||||
|
||||
# Welcome to ScoreSpot
|
||||
|
||||
@@ -14,19 +14,19 @@ Whether you're looking to keep track of your favorite team's performance or simp
|
||||
|
||||
### Homepage
|
||||
|
||||
<img src="public/images/home-page.png" width="90%"/>
|
||||
<img src="public/assets/img/readMe/home-page.png" width="90%"/>
|
||||
|
||||
### Leagues Page
|
||||
|
||||
<img src="public/images/league-page.png" width="90%"/>
|
||||
<img src="public/assets/img/readMe/league-page.png" width="90%"/>
|
||||
|
||||
### Individual Club Page
|
||||
|
||||
<img src="public/images/club-page.png" width="90%"/>
|
||||
<img src="public/assets/img/readMe/club-page.png" width="90%"/>
|
||||
|
||||
### Account Management
|
||||
|
||||
<img src="public/images/account-page.png" width="90%"/>
|
||||
<img src="public/assets/img/readMe/account-page.png" width="90%"/>
|
||||
|
||||
# Technology Stack
|
||||
|
||||
@@ -56,8 +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://github.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**
|
||||
|
||||
@@ -71,24 +70,18 @@ With its sophisticated tech setup, ScoreSpot brings innovation to soccer stat tr
|
||||
|
||||
`cd /c/Users/<YourUsername>` <--- Replace with your windows user name
|
||||
|
||||
|
||||
|
||||
2. In the home directory create a folder called `programming`
|
||||
|
||||
> On All Systems
|
||||
|
||||
`mkdir programming`
|
||||
|
||||
|
||||
|
||||
3. Now that `programming` is created navigate to it
|
||||
|
||||
> On All Systems
|
||||
|
||||
`cd programming`
|
||||
|
||||
|
||||
|
||||
4. **Now that you're in the `~/programming` directory it's time to clone the repository**
|
||||
|
||||
> On All Systems
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
version: '3.9'
|
||||
version: "3.9"
|
||||
|
||||
services:
|
||||
db:
|
||||
@@ -9,14 +9,14 @@ services:
|
||||
POSTGRES_PASSWORD: "pwd"
|
||||
POSTGRES_DB: "users_db"
|
||||
ports:
|
||||
- '5432:5432'
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- users-database:/var/lib/postgresql/data
|
||||
- ./public/init_data:/docker-entrypoint-initdb.d
|
||||
- src/init_data:/docker-entrypoint-initdb.d
|
||||
web:
|
||||
container_name: node-web-interface
|
||||
image: node:lts
|
||||
user: 'node'
|
||||
user: "node"
|
||||
working_dir: /home/node/app
|
||||
environment:
|
||||
NODE_ENV: development
|
||||
@@ -25,11 +25,11 @@ services:
|
||||
depends_on:
|
||||
- db
|
||||
ports:
|
||||
- '3000:3000'
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- .:/home/node/app # Mount Client directory
|
||||
- ./node_modules:/home/node/app/node_modules # Mount node_modules directory
|
||||
command: 'npm run start'
|
||||
command: "npm run start"
|
||||
|
||||
volumes:
|
||||
users-database:
|
||||
|
||||
368
index.js
@@ -1,368 +0,0 @@
|
||||
// *****************************************************
|
||||
// <!-- Section 1 : Import Dependencies -->
|
||||
// *****************************************************
|
||||
|
||||
const express = require('express'); // To build an application server or API
|
||||
const app = express();
|
||||
const handlebars = require('express-handlebars');
|
||||
const Handlebars = require('handlebars');
|
||||
const path = require('path');
|
||||
const pgp = require('pg-promise')(); // To connect to the Postgres DB from the node server
|
||||
const bodyParser = require('body-parser');
|
||||
const session = require('express-session'); // To set the session object. To store or access session data, use the `req.session`, which is (generally) serialized as JSON by the store.
|
||||
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
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 2 : Connect to DB -->
|
||||
// *****************************************************
|
||||
|
||||
// create `ExpressHandlebars` instance and configure the layouts and partials dir.
|
||||
const hbs = handlebars.create({
|
||||
extname: 'hbs',
|
||||
layoutsDir: __dirname + '/src/views/layouts',
|
||||
partialsDir: __dirname + '/src/views/partials',
|
||||
});
|
||||
|
||||
// database configuration
|
||||
// database configuration
|
||||
const dbConfig = {
|
||||
host: 'db', // the database server
|
||||
port: 5432, // the database port
|
||||
database: "users_db", // the database name
|
||||
user: "postgres", // the user account to connect with
|
||||
password: "pwd", // the password of the user account
|
||||
};
|
||||
|
||||
|
||||
const db = pgp(dbConfig);
|
||||
|
||||
// test your database
|
||||
db.connect()
|
||||
.then(obj => {
|
||||
console.log('Database connection successful'); // you can view this message in the docker compose logs
|
||||
obj.done(); // success, release the connection;
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('ERROR:', error.message || error);
|
||||
});
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 3 : App Settings -->
|
||||
// *****************************************************
|
||||
|
||||
// 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, '/src/views'));
|
||||
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,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
extended: true,
|
||||
})
|
||||
);
|
||||
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();
|
||||
});
|
||||
|
||||
// Serve static files from the 'public' directory
|
||||
app.use(express.static(path.join(__dirname, '/src/assets')));
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 4 : Middleware -->
|
||||
// *****************************************************
|
||||
|
||||
// Middleware to automatically update live scoreboard
|
||||
const fetchMatchesData = require('./src/assets/middleware/navigation-bar/current-match-information');
|
||||
app.use(fetchMatchesData);
|
||||
|
||||
//Middleware to automatically update in-game time abbreviations
|
||||
|
||||
const convert_time = require('./src/assets/middleware/navigation-bar/convert-time');
|
||||
app.use(convert_time);
|
||||
|
||||
|
||||
// Leagues Page Middleware
|
||||
|
||||
const fetchLeaguesData = require('./src/assets/middleware/leagues-page/get-current-league-information');
|
||||
const fetchLeagueScorerData = require('./src/assets/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
|
||||
|
||||
const fetchClubsData = require('./src/assets/middleware/clubs-page/get-current-club-information');
|
||||
|
||||
app.get('/club/:clubID', [fetchClubsData], (req, res) => {
|
||||
// Render the Handlebars view with league data
|
||||
|
||||
var isFav = false;
|
||||
var fav_teams = res.locals.fav_teams;
|
||||
if(res.locals.user && fav_teams)
|
||||
{
|
||||
const isTeamIDInFavTeams = fav_teams.some(team => {
|
||||
const teamIdInt = parseInt(team.teamid);
|
||||
const clubIdInt = parseInt(req.params.clubID);
|
||||
console.log('Checking team:', teamIdInt);
|
||||
console.log('equal to', clubIdInt);
|
||||
return teamIdInt === clubIdInt;
|
||||
});
|
||||
if (isTeamIDInFavTeams) {
|
||||
isFav = true
|
||||
}
|
||||
}
|
||||
res.render('pages/clubs-page', {
|
||||
isFav: isFav,
|
||||
clubID: req.params.clubID,
|
||||
clubs: res.locals.club
|
||||
});
|
||||
});
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 5 : API 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
|
||||
*************************/
|
||||
|
||||
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
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/************************
|
||||
League Page Routes
|
||||
*************************/
|
||||
|
||||
// Import and call generateLeagueRoutes function
|
||||
const generateLeagueRoutes = require('./src/assets/routes/league-pages/generate-league-routes');
|
||||
generateLeagueRoutes(app);
|
||||
|
||||
/************************
|
||||
Club Page Routes
|
||||
*************************/
|
||||
|
||||
// Import and call generateLeagueRoutes function
|
||||
const generateClubRoutes = require('./src/assets/routes/club-pages/generate-club-routes');
|
||||
generateClubRoutes(app);
|
||||
|
||||
/************************
|
||||
Favorite Team Database
|
||||
*************************/
|
||||
|
||||
// Function to add a new row to the FavoriteTeams table
|
||||
// database configuration
|
||||
|
||||
app.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' });
|
||||
}
|
||||
});
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 5 : Start Server-->
|
||||
// *****************************************************
|
||||
// starting the server and keeping the connection open to listen for more requests
|
||||
module.exports = app.listen(3000);
|
||||
console.log('Server is listening on port 3000');
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "scorespot",
|
||||
"main": "index.js",
|
||||
"main": "src/index.js",
|
||||
"dependencies": {
|
||||
"axios": "^1.1.3",
|
||||
"bcrypt": "^5.1.0",
|
||||
|
||||
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 7.5 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 5.8 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 43 KiB After Width: | Height: | Size: 43 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 4.7 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 127 KiB After Width: | Height: | Size: 127 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 7.7 KiB After Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
|
Before Width: | Height: | Size: 2.8 KiB After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 2.0 MiB After Width: | Height: | Size: 2.0 MiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 2.1 MiB After Width: | Height: | Size: 2.1 MiB |
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
25
public/views/partials/footer.hbs
Normal file
@@ -0,0 +1,25 @@
|
||||
<footer class="text-center text-muted w-100 mt-auto fixed-bottom">
|
||||
<p>
|
||||
© 2024 - CSCI 3308 Group 6
|
||||
</p>
|
||||
|
||||
<!-- Navigation Bar Scripts -->
|
||||
<script src="/js/navigation-bar/navigation-bar-follow.js"></script>
|
||||
<script
|
||||
src="/js/navigation-bar/user/login-and-register-page-linking.js"
|
||||
></script>
|
||||
<script
|
||||
src="/js/navigation-bar/user/delete-account-favorite-club.js"
|
||||
></script>
|
||||
|
||||
<!-- Homepage Scripts -->
|
||||
<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="/routes/club-pages/redirect-to-club-url.js"></script>
|
||||
|
||||
<!-- Club Pages Scripts -->
|
||||
<script src="/js/club-page/favorite-button.js"></script>
|
||||
|
||||
</footer>
|
||||
|
Before Width: | Height: | Size: 29 KiB |
406
src/index.js
Normal file
@@ -0,0 +1,406 @@
|
||||
// *****************************************************
|
||||
// <!-- Section 1 : Import Dependencies -->
|
||||
// *****************************************************
|
||||
|
||||
const express = require("express"); // To build an application server or API
|
||||
const app = express();
|
||||
const handlebars = require("express-handlebars");
|
||||
const Handlebars = require("handlebars");
|
||||
const path = require("path");
|
||||
const pgp = require("pg-promise")(); // To connect to the Postgres DB from the node server
|
||||
const bodyParser = require("body-parser");
|
||||
const session = require("express-session"); // To set the session object. To store or access session data, use the `req.session`, which is (generally) serialized as JSON by the store.
|
||||
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
|
||||
|
||||
// *****************************************************
|
||||
// <!-- 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",
|
||||
});
|
||||
|
||||
// database configuration
|
||||
// database configuration
|
||||
const dbConfig = {
|
||||
host: "db", // the database server
|
||||
port: 5432, // the database port
|
||||
database: "users_db", // the database name
|
||||
user: "postgres", // the user account to connect with
|
||||
password: "pwd", // the password of the user account
|
||||
};
|
||||
|
||||
const db = pgp(dbConfig);
|
||||
|
||||
// test your database
|
||||
db.connect()
|
||||
.then((obj) => {
|
||||
console.log("Database connection successful"); // you can view this message in the docker compose logs
|
||||
obj.done(); // success, release the connection;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log("ERROR:", error.message || error);
|
||||
});
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 3 : App Settings -->
|
||||
// *****************************************************
|
||||
|
||||
// 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(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,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(
|
||||
bodyParser.urlencoded({
|
||||
extended: true,
|
||||
})
|
||||
);
|
||||
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();
|
||||
});
|
||||
|
||||
// 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 -->
|
||||
// *****************************************************
|
||||
|
||||
// Middleware to automatically update live scoreboard
|
||||
const fetchMatchesData = require("./middleware/navigation-bar/current-match-information");
|
||||
app.use(fetchMatchesData);
|
||||
|
||||
//Middleware to automatically update in-game time abbreviations
|
||||
|
||||
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
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// Clubs Page Middleware
|
||||
|
||||
const fetchClubsData = require("./middleware/clubs-page/get-current-club-information");
|
||||
|
||||
app.get("/club/:clubID", [fetchClubsData], (req, res) => {
|
||||
// Render the Handlebars view with league data
|
||||
|
||||
var isFav = false;
|
||||
var fav_teams = res.locals.fav_teams;
|
||||
if (res.locals.user && fav_teams) {
|
||||
const isTeamIDInFavTeams = fav_teams.some((team) => {
|
||||
const teamIdInt = parseInt(team.teamid);
|
||||
const clubIdInt = parseInt(req.params.clubID);
|
||||
console.log("Checking team:", teamIdInt);
|
||||
console.log("equal to", clubIdInt);
|
||||
return teamIdInt === clubIdInt;
|
||||
});
|
||||
if (isTeamIDInFavTeams) {
|
||||
isFav = true;
|
||||
}
|
||||
}
|
||||
res.render("pages/clubs-page", {
|
||||
isFav: isFav,
|
||||
clubID: req.params.clubID,
|
||||
clubs: res.locals.club,
|
||||
});
|
||||
});
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 5 : API 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
|
||||
*************************/
|
||||
|
||||
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
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/************************
|
||||
League Page Routes
|
||||
*************************/
|
||||
|
||||
// Import and call generateLeagueRoutes function
|
||||
const generateLeagueRoutes = require("./routes/league-pages/generate-league-routes");
|
||||
generateLeagueRoutes(app);
|
||||
|
||||
/************************
|
||||
Club Page Routes
|
||||
*************************/
|
||||
|
||||
// Import and call generateLeagueRoutes function
|
||||
const generateClubRoutes = require("./routes/club-pages/generate-club-routes");
|
||||
generateClubRoutes(app);
|
||||
|
||||
/************************
|
||||
Favorite Team Database
|
||||
*************************/
|
||||
|
||||
// Function to add a new row to the FavoriteTeams table
|
||||
// database configuration
|
||||
|
||||
app.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" });
|
||||
}
|
||||
});
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// *****************************************************
|
||||
// <!-- Section 5 : Start Server-->
|
||||
// *****************************************************
|
||||
// starting the server and keeping the connection open to listen for more requests
|
||||
module.exports = app.listen(3000);
|
||||
console.log("Server is listening on port 3000");
|
||||
@@ -1,21 +0,0 @@
|
||||
<footer class="text-center text-muted w-100 mt-auto fixed-bottom">
|
||||
<p>
|
||||
© 2024 - CSCI 3308 Group 6
|
||||
</p>
|
||||
|
||||
<!-- Navigation Bar Scripts -->
|
||||
<script src="/js/navigation-bar/navigation-bar-follow.js"></script>
|
||||
<script src="/js/navigation-bar/user/login-and-register-page-linking.js"></script>
|
||||
<script src="/js/navigation-bar/user/delete-account-favorite-club.js"></script>
|
||||
|
||||
<!-- Homepage Scripts -->
|
||||
<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="/routes/club-pages/redirect-to-club-url.js"></script>
|
||||
|
||||
<!-- Club Pages Scripts -->
|
||||
<script src="/js/club-page/favorite-button.js"></script>
|
||||
|
||||
</footer>
|
||||
@@ -1,28 +1,27 @@
|
||||
|
||||
// ********************** Initialize server **********************************
|
||||
|
||||
const server = require('../client/src/index.js'); //TODO: Make sure the path to your index.js is correctly added
|
||||
const server = require("../src/index.js"); //TODO: Make sure the path to your index.js is correctly added
|
||||
|
||||
// ********************** Import Libraries ***********************************
|
||||
|
||||
const chai = require('chai'); // Chai HTTP provides an interface for live integration testing of the API's.
|
||||
const chaiHttp = require('chai-http');
|
||||
const chai = require("chai"); // Chai HTTP provides an interface for live integration testing of the API's.
|
||||
const chaiHttp = require("chai-http");
|
||||
chai.should();
|
||||
chai.use(chaiHttp);
|
||||
const {assert, expect} = chai;
|
||||
const { assert, expect } = chai;
|
||||
|
||||
// ********************** DEFAULT WELCOME TESTCASE ****************************
|
||||
|
||||
describe('Server!', () => {
|
||||
describe("Server!", () => {
|
||||
// Sample test case given to test / endpoint.
|
||||
it('Returns the default welcome message', done => {
|
||||
it("Returns the default welcome message", (done) => {
|
||||
chai
|
||||
.request(server)
|
||||
.get('/welcome')
|
||||
.get("/welcome")
|
||||
.end((err, res) => {
|
||||
expect(res).to.have.status(200);
|
||||
expect(res.body.status).to.equals('success');
|
||||
assert.strictEqual(res.body.message, 'Welcome!');
|
||||
expect(res.body.status).to.equals("success");
|
||||
assert.strictEqual(res.body.message, "Welcome!");
|
||||
done();
|
||||
});
|
||||
});
|
||||
@@ -32,16 +31,17 @@ describe('Server!', () => {
|
||||
|
||||
// ********************************************************************************
|
||||
|
||||
describe('Testing Add User API', () => {
|
||||
it('positive: /register', done => {
|
||||
describe("Testing Add User API", () => {
|
||||
it("positive: /register", (done) => {
|
||||
// Define mock user data
|
||||
const userData = {
|
||||
username: 'Test User',
|
||||
password: '123456'
|
||||
username: "Test User",
|
||||
password: "123456",
|
||||
};
|
||||
// Make a POST request to /register with mock user data
|
||||
chai.request(server)
|
||||
.post('/register')
|
||||
chai
|
||||
.request(server)
|
||||
.post("/register")
|
||||
.send(userData)
|
||||
.end((err, res) => {
|
||||
// Assertions
|
||||
@@ -49,70 +49,71 @@ describe('Server!', () => {
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
//We are checking POST /add_user API by passing the user info in in incorrect manner (name cannot be an integer). This test case should pass and return a status 400 along with a "Invalid input" message.
|
||||
//We are checking POST /add_user API by passing the user info in in incorrect manner (name cannot be an integer). This test case should pass and return a status 400 along with a "Invalid input" message.
|
||||
|
||||
describe('Testing Add User API', () => {
|
||||
it('Negative: /register. Checking invalid name', done => {
|
||||
chai.request(server)
|
||||
.post('/register')
|
||||
.send({ Username: 10, Password: '2020-02-20'})
|
||||
describe("Testing Add User API", () => {
|
||||
it("Negative: /register. Checking invalid name", (done) => {
|
||||
chai
|
||||
.request(server)
|
||||
.post("/register")
|
||||
.send({ Username: 10, Password: "2020-02-20" })
|
||||
.end((err, res) => {
|
||||
// Assertions
|
||||
expect(res).to.have.status(400);
|
||||
expect(res.body.message).to.equals('Invalid input');
|
||||
expect(res.body.message).to.equals("Invalid input");
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Testing Render', () => {
|
||||
describe("Testing Render", () => {
|
||||
// Sample test case given to test /test endpoint.
|
||||
it('test "/login" route should render with an html response', done => {
|
||||
it('test "/login" route should render with an html response', (done) => {
|
||||
chai
|
||||
.request(server)
|
||||
.get('/login') // for reference, see lab 8's login route (/login) which renders home.hbs
|
||||
.get("/login") // for reference, see lab 8's login route (/login) which renders home.hbs
|
||||
.end((err, res) => {
|
||||
res.should.have.status(200); // Expecting a success status code
|
||||
res.should.be.html; // Expecting a HTML response
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
var cookies;
|
||||
});
|
||||
var cookies;
|
||||
|
||||
describe('Login', () => {
|
||||
describe("Login", () => {
|
||||
// Sample test case given to test /login endpoint.
|
||||
it('Returns the default welcome message', done => {
|
||||
it("Returns the default welcome message", (done) => {
|
||||
chai
|
||||
.request(server)
|
||||
.get('/login')
|
||||
.get("/login")
|
||||
.end((err, res) => {
|
||||
if (res.headers['set-cookie']) {
|
||||
if (res.headers["set-cookie"]) {
|
||||
// Save the cookies
|
||||
cookies = res.headers['set-cookie'].pop().split(';')[0];
|
||||
cookies = res.headers["set-cookie"].pop().split(";")[0];
|
||||
} else {
|
||||
cookies = null;
|
||||
}
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('Home', () => {
|
||||
});
|
||||
describe("Home", () => {
|
||||
// Sample test case given to test /login endpoint.
|
||||
it('Returns the default welcome message', done => {
|
||||
it("Returns the default welcome message", (done) => {
|
||||
chai
|
||||
.request(server)
|
||||
.get('/home')
|
||||
.get("/home")
|
||||
.end((err, res) => {
|
||||
if (res.headers['set-cookie']) {
|
||||
if (res.headers["set-cookie"]) {
|
||||
// Save the cookies
|
||||
cookies = res.headers['set-cookie'].pop().split(';')[0];
|
||||
cookies = res.headers["set-cookie"].pop().split(";")[0];
|
||||
} else {
|
||||
cookies = null;
|
||||
}
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||