Merge branch 'develop' into 'testing'

Move v1.1 to testing

See merge request sudoer777/score-tracker!14
main
Ethan Reece 2021-12-07 18:29:48 +00:00
commit e6ffa52708
16 changed files with 222 additions and 52 deletions

View File

@ -6,6 +6,8 @@ PGPASSWORD=dbuserpassword
PGDATABASE=mydatabase
PGPORT=5432
PUBLIC_SUBMIT_PAGE=false
#MAIL_FROM=fromaddress@example.com
#MAIL_HOST=smtp.smtphost.net
#MAIL_PORT=465

View File

@ -26,6 +26,7 @@ This repository is designed to be pushed to Heroku/Dokku/etc.
- `PGDATABASE` - set to the name of your database (i.e. `scoretrackerdb`)
- `PGUSER` - set to the user for managing the database
- `PGPASSWORD` - set to the password for that user
- `PUBLIC_SUBMIT_PAGE` (default: `false`) - set to `true` to allow score submissions without an account
## Code

View File

@ -4,10 +4,11 @@ const localStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
class User {
constructor(id, email, isAdmin) {
constructor(id, email, isAdmin, name) {
this.id = id;
this.email = email;
this.isAdmin = isAdmin;
this.name = name;
}
}
@ -75,62 +76,64 @@ async function generateHash(password) {
return bcrypt.hashSync(password, salt);
}
async function create(email, password, isAdmin) {
async function create(email, password, isAdmin, name) {
const hash = await generateHash(password);
const query = `INSERT INTO accounts.users(email, password, admin)
VALUES($1, $2, $3)`;
await database.executeQuery(query, [email, hash, isAdmin]);
const query = `INSERT INTO accounts.users(email, password, admin, full_name)
VALUES($1, $2, $3, $4)`;
await database.executeQuery(query, [email, hash, isAdmin, name]);
}
async function edit(id, email, password, isAdmin) {
async function edit(id, email, password, isAdmin, name) {
if(password) {
const hash = await generateHash(password);
const query = `UPDATE accounts.users
SET email = $2,
password = $3,
admin = $4
admin = $4,
full_name = $5
WHERE user_id = $1;`;
await database.executeQuery(query, [id, email, hash, isAdmin]);
await database.executeQuery(query, [id, email, hash, isAdmin, name]);
} else {
const query = `UPDATE accounts.users
SET email = $2,
admin = $3
admin = $3,
full_name = $4
WHERE user_id = $1;`;
await database.executeQuery(query, [id, email, isAdmin]);
await database.executeQuery(query, [id, email, isAdmin, name]);
}
return new User(id, email, isAdmin);
return new User(id, email, isAdmin, name);
}
async function remove(id) {
const query = `DELETE FROM accounts.users
WHERE user_id = $1
RETURNING email, admin;`;
RETURNING email, admin, full_name;`;
const row = (await database.executeQuery(query, [id]))[0];
return new User(id, row[0], row[1]);
return new User(id, row[0], row[1], row[2]);
}
async function retrieveAll() {
const query = `SELECT user_id, email, admin
const query = `SELECT user_id, email, admin, full_name
FROM accounts.users
ORDER BY email;`
ORDER BY full_name;`;
const table = await database.executeQuery(query);
const accountsList = [];
table.forEach((row) => {
accountsList.push(new User(row[0], row[1], row[2]));
accountsList.push(new User(row[0], row[1], row[2], row[3]));
});
return accountsList;
}
async function getFromID(id) {
const query = `SELECT user_id, email, admin
const query = `SELECT user_id, email, admin, full_name
FROM accounts.users
WHERE user_id = $1;`;
const row = (await database.executeQuery(query, [id]))[0];
return new User(id, row[1], row[2]);
return new User(id, row[1], row[2], row[3]);
}
exports.create = create;

View File

@ -27,17 +27,40 @@ async function Initialize() {
async function checkForDatabaseInitialization() {
const scoresSchemaExistsQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`;
let result = await executeQuery(scoresSchemaExistsQuery);
const databaseIsSetupQuery = `SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'scores'`;
let result = await executeQuery(databaseIsSetupQuery);
const scoresSchemaExists = result.length !== 0;
const databaseIsSetup = result.length !== 0;
if(!scoresSchemaExists) {
if(!databaseIsSetup) {
await Initialize();
}
let latestMigration;
try {
const latestMigrationQuery = `SELECT value FROM metadata WHERE property = 'latest_migration';`;
latestMigration = +((await executeQuery(latestMigrationQuery))[0][0]);
} catch {
latestMigration = 0;
}
await performMigrations(latestMigration);
}
const initializationStatus = checkForDatabaseInitialization();
async function performMigrations(currentMigration) {
const migrationFileList = fs.readdirSync('database/migrations');
const latestMigration = +migrationFileList[migrationFileList.length - 1].slice(0, 1);
for(let i = +currentMigration + 1; i <= latestMigration; i++) {
const sql = fs.readFileSync(`database/migrations/${i}.sql`).toString();
await executeQuery(sql);
console.log(`Performed database migration ${i}`);
}
}

View File

@ -15,14 +15,14 @@ scores:
*season_id* | school_year
games:
*game_id* | ~division_id~ | ~season_id~ | game_date | ~team1_id~ | ~team2_id~ | team1_score | team2_score | ~submitter_id~ | updated_timestamp
*game_id* | ~division_id~ | ~season_id~ | game_date | ~team1_id~ | ~team2_id~ | team1_score | team2_score | ~submitter_id~ | updated_timestamp | submitter_name
accounts:
users:
*user_id* | email | password | admin
*user_id* | email | password | admin | full_name
*/
@ -37,6 +37,7 @@ CREATE TABLE IF NOT EXISTS accounts.users(
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
admin BOOLEAN NOT NULL DEFAULT FALSE,
full_name TEXT NOT NULL,
PRIMARY KEY(user_id)
);
@ -90,7 +91,8 @@ CREATE TABLE IF NOT EXISTS scores.games(
team2_id BIGINT NOT NULL,
team1_score INTEGER NOT NULL,
team2_score INTEGER NOT NULL,
submitter_id BIGINT NOT NULL,
submitter_name TEXT,
submitter_id BIGINT,
updated_timestamp TIMESTAMP WITH TIME ZONE DEFAULT now(),
PRIMARY KEY(game_id),
CONSTRAINT fk_division
@ -110,4 +112,13 @@ CREATE TABLE IF NOT EXISTS scores.games(
REFERENCES accounts.users(user_id)
);
CREATE TABLE IF NOT EXISTS metadata(
property TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
);
INSERT INTO metadata(property, value)
VALUES("latest_migration", "3");
COMMIT;

View File

@ -0,0 +1,13 @@
/* ADD METADATA TABLE */
BEGIN;
CREATE TABLE IF NOT EXISTS metadata(
property TEXT UNIQUE NOT NULL,
value TEXT NOT NULL
);
INSERT INTO metadata(property, value)
VALUES('latest_migration', '1');
COMMIT;

View File

@ -0,0 +1,12 @@
/* ADD ACCOUNT NAME COLUMN */
BEGIN;
ALTER TABLE accounts.users
ADD COLUMN full_name TEXT;
UPDATE metadata
SET value = '2'
WHERE property = 'latest_migration';
COMMIT;

View File

@ -0,0 +1,15 @@
/* ADD OPTIONAL SUBMITTER NAME COLUMN IN GAMES TABLE */
BEGIN;
ALTER TABLE scores.games ALTER COLUMN submitter_id DROP NOT NULL;
ALTER TABLE scores.games
ADD COLUMN submitter_name TEXT;
UPDATE metadata
SET value = '3'
WHERE property = 'latest_migration';
COMMIT;

View File

@ -5,7 +5,7 @@ const database = require('./../database');
class Game {
constructor(id, date, team1ID, team2ID, team1Score, team2Score, divisionID, seasonID, submitterID) {
constructor(id, date, team1ID, team2ID, team1Score, team2Score, divisionID, seasonID, submitterID, submitterName) {
this.id = id;
this.date = date;
this.team1ID = team1ID;
@ -15,17 +15,26 @@ class Game {
this.divisionID = divisionID;
this.seasonID = seasonID;
this.submitterID = submitterID;
this.submitterName = submitterName;
}
}
async function add(divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, userID) {
const query = `INSERT INTO scores.games(division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score, submitter_id)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING game_id;`;
async function add(divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, submitterID, submitterName = undefined) {
let id;
if(submitterName) {
const query = `INSERT INTO scores.games(division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score, submitter_name)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING game_id;`;
id = (await database.executeQuery(query, [divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, submitterName]))[0][0];
} else {
const query = `INSERT INTO scores.games(division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score, submitter_id)
VALUES($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING game_id;`;
id = (await database.executeQuery(query, [divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, submitterID]))[0][0];
}
const id = (await database.executeQuery(query, [divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, userID]))[0][0];
return new Game(id, date, team1ID, team2ID, team1Score, team2Score);
}
@ -41,14 +50,14 @@ async function retrieve(teamID, divisionID, seasonID) {
let table;
if(teamID && divisionID && seasonID) {
const query = `SELECT game_id, division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score
const query = `SELECT game_id, division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score, submitter_id, submitter_name
FROM scores.games
WHERE (team1_id = $1 OR team2_id = $1) AND division_id = $2 AND season_id = $3
ORDER BY game_date DESC;`;
table = await database.executeQuery(query, [teamID,divisionID,seasonID]);
}
else {
const query = `SELECT game_id, division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score
const query = `SELECT game_id, division_id, season_id, game_date, team1_id, team2_id, team1_score, team2_score, submitter_id, submitter_name
FROM scores.games
ORDER BY game_date DESC;`;
table = await database.executeQuery(query);
@ -63,10 +72,10 @@ async function retrieve(teamID, divisionID, seasonID) {
const teamScore = opponentIsTeam2 ? row[6] : row[7];
const opponentScore = opponentIsTeam2 ? row[7] : row[6];
gamesList.push(new Game(row[0], row[3].toISOString().slice(0,10), teamID, opponentID, teamScore, opponentScore, row[1], row[2]));
gamesList.push(new Game(row[0], row[3].toISOString().slice(0,10), teamID, opponentID, teamScore, opponentScore, row[1], row[2], row[8], row[9]));
}
else {
gamesList.push(new Game(row[0], row[3].toISOString().slice(0,10), row[4], row[5], row[6], row[7], row[1], row[2]));
gamesList.push(new Game(row[0], row[3].toISOString().slice(0,10), row[4], row[5], row[6], row[7], row[1], row[2], row[8], row[9]));
}
});
return gamesList;

View File

@ -232,6 +232,10 @@ CATEGORIES.push(new Category(
dateHeader.textContent = "Date";
headerRow.appendChild(dateHeader);
const submitterHeader = document.createElement('th');
submitterHeader.textContent = "Submitter";
headerRow.appendChild(submitterHeader);
itemsListTable.appendChild(headerRow);
},
function listGame(game, row) {
@ -285,6 +289,16 @@ CATEGORIES.push(new Category(
dateSpan.textContent = game.date.slice(5);
dateCell.appendChild(dateSpan);
row.appendChild(dateCell);
const submitterCell = document.createElement('td');
if(game.submitterID) {
Data.getAccount(game.submitterID)
.then(data => submitterCell.textContent = data.name);
} else {
submitterCell.textContent = game.submitterName;
console.log(game.submitterName);
}
row.appendChild(submitterCell);
},
async function addGame() {
window.location.href = "/manage/game";
@ -302,6 +316,10 @@ CATEGORIES.push(new Category(
async function listAccountHeaders() {
const headerRow = document.createElement('tr');
const nameHeader = document.createElement('th');
nameHeader.textContent = "Name";
headerRow.appendChild(nameHeader);
const emailHeader = document.createElement('th');
emailHeader.textContent = "Email";
headerRow.appendChild(emailHeader);
@ -317,6 +335,10 @@ CATEGORIES.push(new Category(
itemsListTable.appendChild(headerRow);
},
function listAccount(account, row) {
const nameCell = document.createElement('td');
nameCell.textContent = account.name;
row.appendChild(nameCell);
const emailCell = document.createElement('td');
emailCell.textContent = account.email;
row.appendChild(emailCell);

View File

@ -2,6 +2,7 @@ import * as Data from "../data.js";
import * as Form from "../form.js";
const submissionForm = document.getElementById('submission-form');
const nameTextbox = document.getElementById('name-textbox');
const emailTextbox = document.getElementById('email-textbox');
const passwordTextbox = document.getElementById('password-textbox');
const adminCheckboxSection = document.getElementById('admin-checkbox-section');
@ -14,7 +15,8 @@ async function Initialize() {
let accountID = params.get('account') || (document.getElementById('account-id') ? document.getElementById('account-id').value : null);
if(accountID) {
const account = await Data.getAccount(accountID);
console.log(account);
nameTextbox.value = account.name;
emailTextbox.value = account.email;
@ -37,6 +39,8 @@ async function Initialize() {
adminCheckboxSection.style.visibility = "visible";
adminCheckbox.disabled = false;
}
nameTextbox.disabled = false;
nameTextbox.addEventListener('keyup', checkDataValidity);
emailTextbox.disabled = false;
emailTextbox.addEventListener('keyup', checkDataValidity);
passwordTextbox.disabled = false;
@ -49,6 +53,7 @@ async function checkDataValidity() {
let dataIsValid = true;
if(!passwordTextbox.value && !passwordTextbox.placeholder) dataIsValid = false;
if(!nameTextbox.value) dataIsValid = false;
if(!emailTextbox.value) dataIsValid = false;
if(dataIsValid) submitButton.disabled = false;

View File

@ -12,6 +12,7 @@ const team1Dropdown = document.getElementById('team1-dropdown');
const team2Dropdown = document.getElementById('team2-dropdown');
const team1ScoreTextbox = document.getElementById('team1-score-textbox');
const team2ScoreTextbox = document.getElementById('team2-score-textbox');
const nameTextbox = document.getElementById('name-textbox');
const submitButton = document.getElementById('submit-button');
const deleteButton = document.getElementById('delete-button');
@ -70,6 +71,9 @@ async function initializeForm() {
team2Dropdown.disabled = false;
team1ScoreTextbox.disabled = false;
team2ScoreTextbox.disabled = false;
if(nameTextbox) {
nameTextbox.disabled = false;
}
sportDropdown.onchange = async () => {
await Form.populateGenders(genderDropdown, sportDropdown.value)
@ -89,6 +93,7 @@ async function initializeForm() {
team1ScoreTextbox.addEventListener('keyup', checkDataValidity);
team2Dropdown.onchange = checkDataValidity;
team2ScoreTextbox.addEventListener('keyup', checkDataValidity);
if(nameTextbox) nameTextbox.addEventListener('keyup', checkDataValidity);
checkDataValidity();
}
@ -112,6 +117,8 @@ async function checkDataValidity() {
if(dateInput.value == "") dataIsValid = false;
if(nameTextbox && nameTextbox.value == "") dataIsValid = false;
submitButton.disabled = !dataIsValid;
}

View File

@ -1,9 +1,12 @@
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'View Scores', userLoggedIn: !!req.user, hideHomeButton: true });
});
router.get('/submit', function(req, res, next) {
res.redirect('/manage/game');
});
module.exports = router;

View File

@ -12,19 +12,47 @@ var accounts = require('../database/accounts/accounts');
var checkLoginStatus = require('./checkLoginStatus');
if (process.env.NODE_ENV !== 'production' || process.env.NODE_ENV !== 'testing') {
require('dotenv').config();
}
router.get('/' ,checkLoginStatus.user, function(req, res, next) {
if(req.user[2]) res.render('manage', { title: 'Management Panel', userLoggedIn: !!req.user });
else res.render('manage/manage-nonadmin', { title: "My Games", userLoggedIn: !!req.user });
});
router.get('/game', checkLoginStatus.user, function(req, res, next) {
let title = req.query.game ? 'Edit Game' : 'Submit Score'
router.get('/game', function(req, res, next) {
if(!(process.env.PUBLIC_SUBMIT_PAGE && process.env.PUBLIC_SUBMIT_PAGE.toLowerCase() == 'true')) {
if (req.user) {
next();
}
else {
res.redirect('/auth/login');
}
} else {
next();
}
},
function(req, res, next) {
let title = req.query.game ? 'Edit Game' : 'Submit Score';
res.render('manage/addgame', { title, userLoggedIn: !!req.user, message: req.flash('error') });
res.render('manage/addgame', { title, userLoggedIn: !!req.user, message: req.flash('error') });
});
router.post('/game', checkLoginStatus.user, async function(req, res, next) {
router.post('/game', function(req, res, next) {
if(!(process.env.PUBLIC_SUBMIT_PAGE && process.env.PUBLIC_SUBMIT_PAGE.toLowerCase() == 'true')) {
if (req.user) {
next();
}
else {
res.redirect('/auth/login');
}
} else {
next();
}
},
async function(req, res, next) {
const id = req.body['game'];
const remove = req.body['remove'];
@ -38,14 +66,20 @@ router.post('/game', checkLoginStatus.user, async function(req, res, next) {
const team1Score = req.body['team1-score'];
const team2ID = req.body['team2'];
const team2Score = req.body['team2-score'];
const userID = req.user[0];
const submitterName = req.body['name'];
const loggedInUserID = req.user[0];
const loggedInUserIsAdmin = req.user[2];
let submitterID;
let loggedInUserID;
let loggedInUserIsAdmin;
if(req.user) {
submitterID = req.user[0];
loggedInUserID = req.user[0];
loggedInUserIsAdmin = req.user[2];
}
const game = id ? await games.getFromID(id) : null;
if(!loggedInUserIsAdmin && game && loggedInUserID != game.submitterID) {
if((!loggedInUserIsAdmin && game && loggedInUserID != game.submitterID) || (!req.user && game)) {
res.status(403).send("ACCESS DENIED");
}
else if(remove) {
@ -57,7 +91,7 @@ router.post('/game', checkLoginStatus.user, async function(req, res, next) {
res.redirect('/manage#games');
}
else {
await games.add(divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, userID);
await games.add(divisionID, seasonID, date, team1ID, team2ID, team1Score, team2Score, submitterID, submitterName);
res.redirect('/');
}
} catch(err) {
@ -189,6 +223,7 @@ router.get('/account', checkLoginStatus.user, (req, res, next) => {
});
router.post('/account', checkLoginStatus.user, async function(req, res, next) {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
@ -206,8 +241,8 @@ router.post('/account', checkLoginStatus.user, async function(req, res, next) {
const isAdmin = loggedInAccountIsAdmin ? !!req.body.admin : false;
if(remove) await accounts.remove(accountID);
else if(accountID) await accounts.edit(accountID, email, password, isAdmin);
else await accounts.create(req.body.email, req.body.password, !!req.body.admin);
else if(accountID) await accounts.edit(accountID, email, password, isAdmin, name);
else await accounts.create(email, password, !!req.body.admin, name);
res.redirect('/manage#accounts');
}

View File

@ -8,10 +8,14 @@ block content
form#submission-form(action='/manage/account', method='POST')
if accountID
input#account-id(type="hidden" name="account" value=accountID)
span(class='form-section')
label Name
span(class='form-section-input')
input#name-textbox(type="text" name="name" disabled)
span(class='form-section')
label Email
span(class='form-section-input')
input#email-textbox(type="email", name="email" disabled)
input#email-textbox(type="email" name="email" disabled)
span(class='form-section')
label Password
span(class='form-section-input' )

View File

@ -45,6 +45,11 @@ block content
label Score
span(class='form-section-input')
input#team2-score-textbox(type="number", name="team2-score", value="0" disabled)
if !userLoggedIn
span(class='form-section')
label Your name
span(class='form-section-input')
input#name-textbox(type="text" name="name" disabled)
.error #{message}
span(class='form-section')
button#submit-button(type="submit" disabled) Submit