1
0
mirror of https://github.com/matt-fidd/stratos.git synced 2026-01-01 18:19:25 +00:00

Lint cleanup with new rules

This commit is contained in:
2022-03-03 09:14:09 +00:00
parent 80291efc6d
commit c9e826d016
20 changed files with 104 additions and 57 deletions

18
app.js
View File

@@ -45,7 +45,7 @@ async function main() {
// Set up express-session to store in mysql database // Set up express-session to store in mysql database
const mysqlStore = require('express-mysql-session')(session); const mysqlStore = require('express-mysql-session')(session);
const sessionStore = const sessionStore =
new mysqlStore({},(await new DatabaseConnectionPool()).pool); new mysqlStore({}, (await new DatabaseConnectionPool()).pool);
// Initialise express app // Initialise express app
const app = express(); const app = express();
@@ -82,9 +82,11 @@ async function main() {
} }
})); }));
// Authentication middleware that redirects unauthenticated users /*
// back to the login page if they request a page they don't have access * Authentication middleware that redirects unauthenticated users
// to * back to the login page if they request a page they don't have access
* to
*/
app.use((req, res, next) => { app.use((req, res, next) => {
const allowed = [ const allowed = [
'/login', '/login',
@@ -116,9 +118,11 @@ async function main() {
for (const route of loadRoutes()) for (const route of loadRoutes())
app.use(route[0], route[1]); app.use(route[0], route[1]);
// If the request gets to the bottom of the route stack, it doesn't /*
// have a defined route and therefore a HTTP status code 404 is sent * If the request gets to the bottom of the route stack, it doesn't
// and an error page shown * have a defined route and therefore a HTTP status code 404 is sent
* and an error page shown
*/
app.use((req, res) => { app.use((req, res) => {
res.status(404).render('error', { res.status(404).render('error', {
title: 'Stratos - Error', title: 'Stratos - Error',

View File

@@ -1,7 +1,7 @@
'use strict'; 'use strict';
// Import required modules // Import required modules
const { dest, parallel, series, src, watch } = require('gulp'); const { dest, parallel, series, src, watch } = require('gulp');
const del = require('del'); const del = require('del');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict'; 'use strict';
const User = require('./User'); const User = require('./User');

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function */
'use strict'; 'use strict';
const DatabaseConnectionPool = require('./DatabaseConnectionPool'); const DatabaseConnectionPool = require('./DatabaseConnectionPool');
@@ -134,11 +135,11 @@ class Class {
})(); })();
} }
async getSubject() { getSubject() {
return new (require('./Subject'))(this.subjectId); return new (require('./Subject'))(this.subjectId);
} }
async getUsers(ids, type) { getUsers(ids, type) {
const types = { const types = {
account: 'Account', account: 'Account',
student: 'Student' student: 'Student'
@@ -212,4 +213,4 @@ class Class {
} }
} }
module.exports = Class; module.exports = Class;

View File

@@ -14,6 +14,7 @@ const defaultDbOptions = importJSON('db');
*/ */
class DatabaseConnectionPool { class DatabaseConnectionPool {
#dbOptions; #dbOptions;
#connectionPool; #connectionPool;
/** /**

View File

@@ -200,7 +200,7 @@ class EmailBuilder {
} }
if (typeof this?.#HTMLBody?.length !== 'undefined') if (typeof this?.#HTMLBody?.length !== 'undefined')
message['html'] = this.#HTMLBody; message.html = this.#HTMLBody;
return message; return message;
} }

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict'; 'use strict';
const User = require('./User'); const User = require('./User');

View File

@@ -7,8 +7,11 @@ const DatabaseConnectionPool = require('./DatabaseConnectionPool');
class PasswordReset { class PasswordReset {
userId; userId;
token; token;
nonce; nonce;
expires; expires;
constructor(userId, token) { constructor(userId, token) {

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict'; 'use strict';
const User = require('./User'); const User = require('./User');

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict'; 'use strict';
// Import user defined modules // Import user defined modules
@@ -105,11 +106,11 @@ class Test {
})(); })();
} }
async getClass() { getClass() {
return new (require('./Class'))(this.classId); return new (require('./Class'))(this.classId);
} }
async getTestTemplate() { getTestTemplate() {
return new (require('./TestTemplate'))(this.templateId); return new (require('./TestTemplate'))(this.templateId);
} }

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-empty-function, getter-return */
'use strict'; 'use strict';
// Import user defined modules // Import user defined modules
@@ -73,7 +74,7 @@ class TestTemplate {
})(); })();
} }
async getAccount() { getAccount() {
return new (require('./Account'))(this.accountId); return new (require('./Account'))(this.accountId);
} }

View File

@@ -11,13 +11,21 @@ const Test = require('./Test');
class User { class User {
id; id;
firstName; firstName;
otherNames; otherNames;
lastName; lastName;
shortName; shortName;
fullName; fullName;
email; email;
#password; #password;
type = null; type = null;
constructor(type, userId) { constructor(type, userId) {
@@ -33,6 +41,9 @@ class User {
} }
return (async () => { return (async () => {
const conn = await new DatabaseConnectionPool();
const queryPromises = [];
for (const type of types) { for (const type of types) {
const sql = ` const sql = `
select select
@@ -48,19 +59,27 @@ class User {
${type}Id = ?; ${type}Id = ?;
`; `;
const conn = await new DatabaseConnectionPool(); queryPromises.push(conn.runQuery(sql, [
const res = userId
await conn.runQuery(sql, [ userId ]); ]));
}
conn.close(); const typeResults = await Promise.all(queryPromises);
conn.close();
if (!res.length) for (const [ i, result ] of typeResults.entries()) {
if (!result.length)
continue; continue;
const record = res[0]; const record = result[0];
const type = types[i];
for (const [ k, v ] of Object.entries(record)) for (const [ k, v ] of Object.entries(record)) {
this[k] = v; if (k === 'password')
this.#password = v;
else
this[k] = v;
}
this.type = type; this.type = type;
this.shortName = this.getShortName(); this.shortName = this.getShortName();
@@ -70,8 +89,8 @@ class User {
return this; return this;
const className = const className =
`${type.substring(0, 1).toUpperCase()}` `${type.substring(0, 1).toUpperCase()}`+
+ `${type.substring(1)}`; `${type.substring(1)}`;
return new (require(`./${className}`))(this.id); return new (require(`./${className}`))(this.id);
} }
@@ -94,7 +113,7 @@ class User {
} }
async verifyPassword(password) { async verifyPassword(password) {
return await bcrypt.compare(password, this.password); return await bcrypt.compare(password, this.#password);
} }
async changePassword(password) { async changePassword(password) {
@@ -173,7 +192,7 @@ class User {
if (this.type === 'parent') if (this.type === 'parent')
throw new Error(`Can not fetch class for ${this.type}`); throw new Error(`Can not fetch class for ${this.type}`);
let sql = ` const sql = `
select select
c.classId as classId c.classId as classId
from from
@@ -243,6 +262,8 @@ class User {
const conn = await new DatabaseConnectionPool(); const conn = await new DatabaseConnectionPool();
const types = [ 'account', 'student', 'parent' ]; const types = [ 'account', 'student', 'parent' ];
const idPromises = [];
for (const type of types) { for (const type of types) {
const sql = ` const sql = `
select select
@@ -253,18 +274,24 @@ class User {
email = ?; email = ?;
`; `;
const id = (await conn.runQuery(sql, [ idPromises.push(conn.runQuery(sql, [
email email
]))?.[0]?.['id']; ]));
}
const ids = await Promise.all(idPromises);
for (const [ i, records ] of ids.entries()) {
const type = types[i];
const id = records?.[0]?.id;
if (typeof id !== 'undefined') { if (typeof id !== 'undefined') {
const className = const className =
`${type.substring(0, 1).toUpperCase()}` `${type.substring(0, 1).toUpperCase()}`+
+ `${type.substring(1)}`; `${type.substring(1)}`;
return new (require(`./${className}`))(id); return new (require(`./${className}`))(id);
} }
} }
} }
} }

View File

@@ -66,7 +66,7 @@ describe('DatabaseConnectionPool', () => {
expect(() => dbp.runQuery(sql, params)).toThrow(); expect(() => dbp.runQuery(sql, params)).toThrow();
}); });
test('Query with whitespace after ; should not fail', ()=> { test('Query with whitespace after ; should not fail', () => {
const dbp = new DatabaseConnectionPool(); const dbp = new DatabaseConnectionPool();
const sql = ` const sql = `

View File

@@ -3,6 +3,6 @@
const helpers = {}; const helpers = {};
helpers.eq = (arg1, arg2, options) => helpers.eq = (arg1, arg2, options) =>
arg1 == arg2 ? options.fn(this) : options.inverse(this); arg1 === arg2 ? options.fn(this) : options.inverse(this);
module.exports = helpers; module.exports = helpers;

View File

@@ -38,9 +38,7 @@ function passwordsMatch(password1, password2) {
* @return {string} - The sanitisied field * @return {string} - The sanitisied field
*/ */
function sanitiseField(field) { function sanitiseField(field) {
let cleanField; const cleanField = field.trim();
cleanField = field.trim();
return cleanField; return cleanField;
} }

View File

@@ -171,7 +171,7 @@ router.get('/password-reset/:uuid/:token', async (req, res) => {
let pr; let pr;
try { try {
pr = await new PasswordReset(uuid, token); pr = await new PasswordReset(uuid, token);
} catch(e) { } catch (e) {
console.error(e); console.error(e);
return res.redirect('/password-reset'); return res.redirect('/password-reset');
} }
@@ -214,7 +214,7 @@ router.post('/change-password', async (req, res) => {
fields.get('uuid'), fields.get('uuid'),
fields.get('token') fields.get('token')
); );
} catch(e) { } catch (e) {
console.error(e); console.error(e);
return res.redirect('/password-reset'); return res.redirect('/password-reset');
} }

View File

@@ -4,13 +4,15 @@ const express = require('express');
const router = express.Router(); const router = express.Router();
router.get('/reports', (req, res, next) => { router.get('/reports', (req, res, next) => {
/* /* eslint-disable multiline-comment-style */
/*
return res.render('reports', { return res.render('reports', {
title: 'Stratos - Reports', title: 'Stratos - Reports',
current: 'Reports', current: 'Reports',
name: req.session.fullName name: req.session.fullName
}); });
*/ */
/* eslint-enable multiline-comment-style */
next(); next();
}); });

View File

@@ -19,12 +19,15 @@ const { data } = require('./testData');
async function cleanDb() { async function cleanDb() {
const conn = await new DatabaseConnectionPool(); const conn = await new DatabaseConnectionPool();
// Remove records from tables in reverse order to which they depend on /*
// each other * Remove records from tables in reverse order to which they depend on
* each other
*/
const tables = Object.keys(data).reverse(); const tables = Object.keys(data).reverse();
tables.push('sessions'); tables.push('sessions');
for (const table of tables) for (const table of tables)
/* eslint-disable-next-line no-await-in-loop */
await conn.runQuery(`DELETE FROM ${table};`); await conn.runQuery(`DELETE FROM ${table};`);
conn.close(); conn.close();

View File

@@ -12,7 +12,6 @@ const tableCreate = new Map();
const tableConstraints = new Map(); const tableConstraints = new Map();
// For each table, set tableCreate.tableName equal to the creation statment // For each table, set tableCreate.tableName equal to the creation statment
// for that table
tableCreate.set('account', ` tableCreate.set('account', `
CREATE TABLE IF NOT EXISTS account ( CREATE TABLE IF NOT EXISTS account (
accountId varchar(36) NOT NULL PRIMARY KEY, accountId varchar(36) NOT NULL PRIMARY KEY,
@@ -128,8 +127,10 @@ tableCreate.set('accountClassLink', `
); );
`); `);
// For each table constraint, set tableConstraints.constraitName equal to the /*
// creation statment for that constraint * For each table constraint, set tableConstraints.constraintName equal to the
* creation statment for that constraint
*/
tableConstraints.set('accountClassLink_fk0', ` tableConstraints.set('accountClassLink_fk0', `
ALTER TABLE accountClassLink ALTER TABLE accountClassLink
ADD CONSTRAINT accountClassLink_fk0 ADD CONSTRAINT accountClassLink_fk0
@@ -260,6 +261,7 @@ async function dbInit() {
console.log(`Creating table ${tableName}`); console.log(`Creating table ${tableName}`);
try { try {
/* eslint-disable-next-line no-await-in-loop */
await conn.runQuery(sql); await conn.runQuery(sql);
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@@ -274,6 +276,7 @@ async function dbInit() {
console.log(`Creating constraint ${fkName}`); console.log(`Creating constraint ${fkName}`);
try { try {
/* eslint-disable-next-line no-await-in-loop */
await conn.runQuery(sql); await conn.runQuery(sql);
} catch (e) { } catch (e) {
console.error(e); console.error(e);

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-await-in-loop */
'use strict'; 'use strict';
// Import required modules // Import required modules
@@ -27,34 +28,33 @@ async function insertTestData() {
for (const record of data[table]) { for (const record of data[table]) {
const dataToInsert = { ...record }; const dataToInsert = { ...record };
if (details?.[table]?.['id'] === 'uuid') { if (details?.[table]?.id === 'uuid') {
dataToInsert[`${table}Id`] = dataToInsert[`${table}Id`] =
crypto.randomUUID(); crypto.randomUUID();
} else { } else {
dataToInsert[`${table}Id`] = counter + 1; dataToInsert[`${table}Id`] = counter + 1;
} }
if (details?.[table]?.['hashPassword']) { if (details?.[table]?.hashPassword) {
dataToInsert['password'] = dataToInsert.password =
await bcrypt.hash( await bcrypt.hash(
dataToInsert['password'], dataToInsert.password,
10); 10);
} }
if (details?.[table]?.['link']) if (details?.[table]?.link)
delete dataToInsert[`${table}Id`]; delete dataToInsert[`${table}Id`];
if (record?.lookups) { if (record?.lookups) {
delete dataToInsert.lookups; delete dataToInsert.lookups;
const lookupsEntries =
Object.entries(record.lookups);
for (let [ key, index ] of for (const [ key, index ] of lookupsEntries) {
Object.entries(record.lookups)) {
const resolveTable = key.split('Id')[0]; const resolveTable = key.split('Id')[0];
index--; const r = data[resolveTable][index - 1];
dataToInsert[key] = dataToInsert[key] = r[key];
data[resolveTable][index][key];
} }
} }