From 302df17cccbec6ef0592da518a01882a0323a7dc Mon Sep 17 00:00:00 2001 From: Tom Berey Date: Sun, 1 Aug 2021 16:34:09 +0100 Subject: [PATCH 1/5] Ver:3.0.2--Minor-Updates --- README.md | 4 ++++ package-lock.json | 6 +++--- package.json | 2 +- src/Server.ts | 36 ++++++++++++++++-------------------- src/ServerSetup.ts | 30 +++++++++++++++--------------- src/SocketsServer.ts | 29 +++++++++++++++++++++-------- src/main.ts | 4 ++-- src/services/Database.ts | 15 ++++++++++----- 8 files changed, 72 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 31cc9c8..1bb1407 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,9 @@ Below is the refined and confirmed roadmap, that has been planned for completion | Bug#1 | Bug details... | 0.0.1 | example#1 | | Feature#4 | Feature details... | | example#2 | | Automatic Database Startup & Configuration | Auto-build database and table(s), and auto-populate data or test account (seeding). | | | +| Fix ID=0, On Register and Login | User's ID is shown as 0, but only when registering and logging in for first time, (relog fixes, & no DB issues seen). | | | +| Remove SQL From Server.ts | Remove any sql/db related stuff from Server.ts class and add into Database.ts class. | | | +| Add Promises | Add Promises etc. | | |


@@ -187,6 +190,7 @@ Below is the refined and confirmed roadmap, that has been planned for completion |Version 2.2.0 | [2020-05-20] | | |Version 3.0.0 | [2021-07-29] | | |Version 3.0.1 | [2021-07-31] | | +|Version 3.0.2 | [2021-08-01] | |


diff --git a/package-lock.json b/package-lock.json index e8740d2..a174370 100644 --- a/package-lock.json +++ b/package-lock.json @@ -304,9 +304,9 @@ } }, "@types/node": { - "version": "14.17.6", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.6.tgz", - "integrity": "sha512-iBxsxU7eswQDGhlr3AiamBxOssaYxbM+NKXVil8jg9yFXvrfEFbDumLD/2dMTB+zYyg7w+Xjt8yuxfdbUHAtcQ==" + "version": "14.17.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.7.tgz", + "integrity": "sha512-SYTdMaW47se8499q8m0fYKZZRlmq0RaRv6oYmlVm6DUm31l0fhOl1D03X8hGxohCKTI2Bg6w7W0TiYB51aJzag==" }, "@types/qs": { "version": "6.9.7", diff --git a/package.json b/package.json index 5cfa1b6..638a5f5 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "@types/express-session": "^1.17.0", "@types/mocha": "^8.2.2", "@types/mysql": "^2.15.18", - "@types/node": "^14.0.1", + "@types/node": "^14.17.7", "@types/socket.io": "^2.1.6", "@typescript-eslint/eslint-plugin": "^4.28.0", "@typescript-eslint/parser": "^4.28.0", diff --git a/src/Server.ts b/src/Server.ts index dacd109..2b3f9f3 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,6 +1,5 @@ -/* eslint-disable */ import { ServerSetup } from "./ServerSetup" -import { Request, Response, NextFunction } from "express"; +import { Request, Response/*, NextFunction*/ } from "express"; import bcrypt from "bcrypt"; export class Server extends ServerSetup { @@ -29,10 +28,8 @@ export class Server extends ServerSetup { private postRequests():void { - - // POST Method for the request made to login, with the details supplied by user queried against the sql db. Set session data and redirect to chat. - this.router.post('/login', (req:Request, res:Response, next: NextFunction):void => { + this.router.post('/login', (req:Request, res:Response/*, next: NextFunction*/):void => { // Capture username and password, supplied with request body from client. const username = req.body.username; @@ -41,13 +38,13 @@ export class Server extends ServerSetup { // Error checking for both username/password combo and return message, else continue with request. if (!username && !password) { res.status(422).render('index', {msg: `Please enter both a Username and Password.`}); - return next(); + //return next(); } else if (username && password) { // Define db sql script to pass in as an argument with the db query function call, to find user attempting to login. - const query = `SELECT * FROM users WHERE username = '${username}'`; - this.db.dbConnection.query(query, (err:Error, results:any /*:Array*/):void => { + const query = `SELECT * FROM ${process.env['DB_TABLE']} WHERE username = '${username}'`; + this.db.dbConnection.query(query, (err:Error, results):void => { // DB Query Error handling. Return error and bad status. if (err) res.status(500).render('index', {msg: err}); @@ -87,7 +84,7 @@ export class Server extends ServerSetup { } }); } - next(); + //next(); }); @@ -106,7 +103,7 @@ export class Server extends ServerSetup { else if (username && password) { // Define our db sql script to check if the submitted username already exists. Query passed in as an argument with the db query function call. - const query = `SELECT * FROM users WHERE username = '${username}'`; // Query db for specific username. + const query = `SELECT * FROM ${process.env['DB_TABLE']} WHERE username = '${username}'`; // Query db for specific username. this.db.dbConnection.query(query, (err:Error, results:Array) => { // DB Query error handling. Return error and bad status. @@ -125,7 +122,7 @@ export class Server extends ServerSetup { if (err) throw err; // Define db query and call function to add new row/user into sql db. - const query = `INSERT INTO users (username, password) VALUES ('${username}','${hash}');`; + const query = `INSERT INTO ${process.env['DB_TABLE']} (username, password) VALUES ('${username}','${hash}');`; this.db.dbConnection.query(query, (err:Error) => { // DB Query error handling. Return error and bad status. @@ -138,7 +135,7 @@ export class Server extends ServerSetup { // Define db query and pass into called function to return the ID of the last inputted user, from this connection specifically. const query = `SELECT LAST_INSERT_ID();`; - this.db.dbConnection.query(query, (err:Error, result:any) => { + this.db.dbConnection.query(query, (err:Error, result) => { // DB Query error handling. Return error and bad status. if (err) res.status(500).render('index', {msg: err}); @@ -180,7 +177,7 @@ export class Server extends ServerSetup { else if (newUsername) { // Define our db sql script, to find the username supplied, and pass in as an argument with db query call. - const query = `SELECT * FROM users WHERE username = '${newUsername}'`; + const query = `SELECT * FROM ${process.env['DB_TABLE']} WHERE username = '${newUsername}'`; this.db.dbConnection.query(query, (err:Error, results:Array) => { // DB Query error handling. Return error and bad status. @@ -192,7 +189,7 @@ export class Server extends ServerSetup { else if (!(results.length)) { // Query to edit the record, contrained by user's current username, with the new username. - const query = `UPDATE users SET username='${newUsername}' WHERE username='${req.session.username}';`; + const query = `UPDATE ${process.env['DB_TABLE']} SET username='${newUsername}' WHERE username='${req.session.username}';`; this.db.dbConnection.query(query, (err:Error) => { // DB Query error handling. Return error and bad status. @@ -258,8 +255,8 @@ export class Server extends ServerSetup { else if (newPassword && currentPassword) { // Define our db sql script to isolate user's password. Pass in query as an argument with the db query function call. - const query = `SELECT password FROM users WHERE username = '${req.session.username}'`; - this.db.dbConnection.query(query, (err:Error, results:any) => { + const query = `SELECT password FROM ${process.env['DB_TABLE']} WHERE username = '${req.session.username}'`; + this.db.dbConnection.query(query, (err:Error, results) => { // DB Query error handling. Return error and bad status. if (err) res.status(500).send(err); // Error handling. Return error and bad status. @@ -284,7 +281,7 @@ export class Server extends ServerSetup { if (err) throw err; // Define sql script to update current db hashed password with new hashed password. Pass into query function call to execute. - const query = `UPDATE users SET password='${hash}' WHERE username='${req.session.username}';`; + const query = `UPDATE ${process.env['DB_TABLE']} SET password='${hash}' WHERE username='${req.session.username}';`; this.db.dbConnection.query(query, (err:Error) => { // DB Query error handling. Return error and bad status. @@ -313,7 +310,7 @@ export class Server extends ServerSetup { else if (req.session.loggedin) { // Define delete query of user, for db query call argument. - const query = `DELETE FROM users WHERE username='${req.session.username}';`; + const query = `DELETE FROM ${process.env['DB_TABLE']} WHERE username='${req.session.username}';`; this.db.dbConnection.query(query, (err:Error) => { // DB Query error handling. Return error and bad status. @@ -330,5 +327,4 @@ export class Server extends ServerSetup { } }); } -} -/* eslint-enable */ \ No newline at end of file +} \ No newline at end of file diff --git a/src/ServerSetup.ts b/src/ServerSetup.ts index 2cbe9d5..06da4ad 100644 --- a/src/ServerSetup.ts +++ b/src/ServerSetup.ts @@ -2,12 +2,12 @@ import { Rollbar } from './services/Rollbar'; import { SimpleTxtLogger } from 'simple-txt-logger'; import { HelperService } from './services/HelperService'; import { Database } from './services/Database'; -import express, { Express, Router } from 'express'; +import express, { Express, Router, RequestHandler } from 'express'; import dotenv from 'dotenv'; import http from 'http'; -import SocketIOServer from "socket.io"; import session from "express-session"; import cookieParser from "cookie-parser"; +import { SocketsServer } from './SocketsServer'; declare module 'express-session' { interface SessionData { @@ -21,15 +21,15 @@ declare module 'express-session' { export class ServerSetup { - protected io: SocketIOServer.Server; - private sessionMiddleware: express.RequestHandler; - static appName = 'Chatroom'; private port: string; private hostname: string; + + private sessionMiddleware: RequestHandler; private server: http.Server; protected router: Router; private app: Express; + private socketServer: SocketsServer protected db: Database; protected txtLogger: SimpleTxtLogger; @@ -46,12 +46,6 @@ export class ServerSetup { this.txtLogger.writeToLogFile('...::SERVER-SIDE APPLICATION STARTING::...'); - this.router = express.Router(); - this.app = express(); - this.server = new http.Server(this.app); - this.io = SocketIOServer(this.server, {'path': '/chat'}); // send to io class? - this.db = new Database(this.txtLogger, this.rollbarLogger); - this.sessionMiddleware = session({ //store: new FileStore(), //store some session data in a db? cookie: { @@ -63,16 +57,18 @@ export class ServerSetup { resave: true }); + this.router = express.Router(); + this.app = express(); + this.server = new http.Server(this.app); + this.socketServer = new SocketsServer(this.server, this.sessionMiddleware); + this.db = new Database(this.txtLogger, this.rollbarLogger); + this.serverConfig(); this.serverStart(); } private serverConfig(): void { - // Express middleware private session data/setup. this.app.use(this.sessionMiddleware); - this.io.use((socket, next) => { - this.sessionMiddleware(socket.request, socket.request.res, next); - }); this.app.use(express.urlencoded({extended: true})); this.app.use(express.json()); @@ -88,6 +84,10 @@ export class ServerSetup { this.server.listen(parseInt(this.port), this.hostname, () => this.txtLogger.writeToLogFile(`Started HTTP Server: http://${this.hostname}:${this.port}`)); } + public closeSocketServer(): void { + this.socketServer.close(); + } + // Accessor needed for testing only. So property 'this.app' can remain private. public appAccessor(app = this.app): Express { return app; diff --git a/src/SocketsServer.ts b/src/SocketsServer.ts index e29a221..ffff1b8 100644 --- a/src/SocketsServer.ts +++ b/src/SocketsServer.ts @@ -1,5 +1,6 @@ -import { Server } from "./Server"; -import { Socket } from "socket.io"; +import SocketIOServer, { Socket } from "socket.io"; +import { Server } from 'http'; +import { RequestHandler } from 'express'; // Define our data profiles as interfaces. interface IUser { @@ -13,15 +14,19 @@ interface IMessage { } // Socket.io server integration handling class. An instance of this is a fully functioning sockets server, which uses the ServerRouter parent classes. -export class SocketsServer extends Server { - - constructor(port?: string, hostname?: string) { - super(port, hostname); +export class SocketsServer { + + private io: SocketIOServer.Server; + + constructor(server: Server, sessionMiddleware: RequestHandler) { + this.io = SocketIOServer(server, {'path': '/chat'}); + this.io.use((socket, next) => sessionMiddleware(socket.request, socket.request.res, next)); + this.socketHandler(); } // Method to handle all socket communication, incoming and outgoing. - private socketHandler():void { + private socketHandler(): void { // Create new Sets (ES6) to hold all chatroom messages history, and connected users list, for a session. const messageSet: Set = new Set(); @@ -41,7 +46,10 @@ export class SocketsServer extends Server { }); // Disconnect user and break out, if the user is not logged in. - if (!(socket.request.session.loggedin)) {socket.disconnect();return;} + if (!(socket.request.session.loggedin)) { + socket.disconnect(); + return; + } // Create a new user, using stored request session properties. const user:IUser = { uniqueID: socket.request.session.uid, name: socket.request.session.username }; @@ -127,4 +135,9 @@ export class SocketsServer extends Server { }); }); } + + public close(): void { + this.io.sockets.emit('disconnect'); + this.io.close(); + } } \ No newline at end of file diff --git a/src/main.ts b/src/main.ts index 4782504..9c9d767 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,4 @@ -import { SocketsServer } from "./SocketsServer"; +import { Server } from "./Server"; -const server:SocketsServer = new SocketsServer(); +const server: Server = new Server(); server; \ No newline at end of file diff --git a/src/services/Database.ts b/src/services/Database.ts index bf4028e..405aa68 100644 --- a/src/services/Database.ts +++ b/src/services/Database.ts @@ -1,7 +1,7 @@ import { Rollbar } from './Rollbar'; import { SimpleTxtLogger } from 'simple-txt-logger'; import { HelperService } from './HelperService'; -import mysql, { Pool } from 'mysql'; +import mysql, { Pool, Query } from 'mysql'; export interface QueryReturnData extends Object { "Ticker_Symbol": string, @@ -44,15 +44,20 @@ export class Database { this.txtLogger.writeToLogFile('Database Disconnected.'); } - public selectAll(): void { - const query = `SELECT * FROM ${this.dbTable} LIMIT 5`; - this.dbConnection.query(query, (err, results): void => { + public login(username: string): Query | number { + const query = `SELECT * FROM ${this.dbTable} WHERE username = '${username}'`; + + return this.dbConnection.query(query, (err, results): number | Query => { + if (err) { this.rollbarLogger.rollbarError(err); - return this.txtLogger.writeToLogFile(`Error reported to Rollbar: ${err}`); + this.txtLogger.writeToLogFile(`Error reported to Rollbar: ${err}`); + const statusCode = 500; + return statusCode; } this.txtLogger.writeToLogFile(`DB Results: ${results}`); + return results; }); } } \ No newline at end of file From e48d9a12515172cf19e84b06a59664339b7c3ad7 Mon Sep 17 00:00:00 2001 From: Tom Berey Date: Sun, 1 Aug 2021 16:35:05 +0100 Subject: [PATCH 2/5] Ver:3.0.2--Minor-Updates --- src/ServerSetup.ts | 2 +- src/{ => services}/SocketsServer.ts | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename src/{ => services}/SocketsServer.ts (100%) diff --git a/src/ServerSetup.ts b/src/ServerSetup.ts index 06da4ad..df77090 100644 --- a/src/ServerSetup.ts +++ b/src/ServerSetup.ts @@ -7,7 +7,7 @@ import dotenv from 'dotenv'; import http from 'http'; import session from "express-session"; import cookieParser from "cookie-parser"; -import { SocketsServer } from './SocketsServer'; +import { SocketsServer } from './services/SocketsServer'; declare module 'express-session' { interface SessionData { diff --git a/src/SocketsServer.ts b/src/services/SocketsServer.ts similarity index 100% rename from src/SocketsServer.ts rename to src/services/SocketsServer.ts From 62020c539a44686ef2d6f495859afc1f04cc759d Mon Sep 17 00:00:00 2001 From: Tom Berey Date: Tue, 3 Aug 2021 20:13:33 +0100 Subject: [PATCH 3/5] Ver:3.0.3--Minor-Updates --- README.md | 23 ++++++++++++----------- src/Server.ts | 20 ++++++++++---------- src/services/Rollbar.ts | 2 +- src/services/SocketsServer.ts | 2 +- src/tests/TestServer.ts | 35 +++++++++++++++++++++++++++++++++++ src/tests/deployment.test.ts | 21 +++++++++++++++++++++ src/tests/spec.test.ts | 29 +++++++++++++++++++++++++++++ views/partials/chatScript.ejs | 4 ++-- 8 files changed, 111 insertions(+), 25 deletions(-) create mode 100644 src/tests/TestServer.ts create mode 100644 src/tests/deployment.test.ts create mode 100644 src/tests/spec.test.ts diff --git a/README.md b/README.md index 1bb1407..98ccbf0 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ A Chatroom Application with User Authentication & Accounts. Login & Register to ### Tech Stack * [Typescript](https://www.typescriptlang.org/) * [NodeJS](https://nodejs.org/en/) -* [Scoket.io](https://socket.io/) +* [Socket.io](https://socket.io/) * [Express](https://expressjs.com/) * [MySQL](https://www.mysql.com/) * [EJS](https://ejs.co/) @@ -156,7 +156,7 @@ Below is the refined and confirmed roadmap, that has been planned for completion | Bug#1 | Bug details... | 0.0.1 | example#1 | | Feature#4 | Feature details... | | example#2 | | Automatic Database Startup & Configuration | Auto-build database and table(s), and auto-populate data or test account (seeding). | | | -| Fix ID=0, On Register and Login | User's ID is shown as 0, but only when registering and logging in for first time, (relog fixes, & no DB issues seen). | | | +| Fix ID=0, On Register and Login | User's ID is shown as 0, but only when registering and logging in for first time, (re-log fixes, & no DB issues seen). | | | | Remove SQL From Server.ts | Remove any sql/db related stuff from Server.ts class and add into Database.ts class. | | | | Add Promises | Add Promises etc. | | | @@ -169,15 +169,15 @@ Below is the refined and confirmed roadmap, that has been planned for completion |Version | Date | Changes | |:---|:---|:---| -|Version 0.0.1 | [2020-03-08] |
  • Initial Commit.
  • Add inital directory structure and files.
  • Build enables users to join, set a name (or not) and chat with each other.
  • Add dynamic 'who is typing' live indicator
  • Set un-changable unique ID to users, to trace all messages back to users.
  • Add logging/informative details about who connects/disconnects.
  • Add timestamp and further styling to messages.
  • Add Screenshots dir, and image screenshot files.
  • Add README.md
| +|Version 0.0.1 | [2020-03-08] |
  • Initial Commit.
  • Add initial directory structure and files.
  • Build enables users to join, set a name (or not) and chat with each other.
  • Add dynamic 'who is typing' live indicator
  • Set un-changeable unique ID to users, to trace all messages back to users.
  • Add logging/informative details about who connects/disconnects.
  • Add timestamp and further styling to messages.
  • Add Screenshots dir, and image screenshot files.
  • Add README.md
| |Version 0.0.2 | [2020-03-09] |
  • Add new set to store chat/conversation history, which is sent to newly connected clients (enables full chat when client joins later/last).
  • Remove 'dist' and 'modules' folders. (After adding gitignore.)
  • Update README.md
| -|Version 0.1.0 | [2020-03-10] |
  • Add connected users list to client-side.
  • Add new IUser type for user's details, and create new set to hold these (and ammend IMessage type to accept this new type in place of exisiting props).
  • Update front-end DOM and appearance, to be more sensical.
  • Update public script to accept newly updated types/interfaces.
  • Update README.md
| +|Version 0.1.0 | [2020-03-10] |
  • Add connected users list to client-side.
  • Add new IUser type for user's details, and create new set to hold these (and amend IMessage type to accept this new type in place of existing props).
  • Update front-end DOM and appearance, to be more coherent.
  • Update public script to accept newly updated types/interfaces.
  • Update README.md
| |Version 0.2.0 | [2020-03-11] |
  • Update connected users list on client-side, plus styling.
  • Update chatroom/message-list to have a scroll (overscroll) feature, for large amounts of messages.
  • Add feature to always scroll to bottom of chatroom/messages-list.
  • Update the user set list to remove contacts on disconnection, and send updated list out to remaining.
  • General code sharpening.
  • Update 'Screenshots' dir, with new images.
  • Update README.md
| |Version 0.2.1 | [2020-03-12] |
  • Add feature to show all users who may be typing concurrently (so more than one at a time).
  • Add server messages feature, to alert connected users of updates to other connected users. I.e. connecting/disconnecting.
  • Fix bug, where when any user sends a message it would clear all user's input field of text.
  • General code sharpening/tidying, and minor client-side DOM adjustments.
  • Update README.md
| |Version 0.2.2 | [2020-03-13] |
  • Friday the 13th Update, spoooky.
  • Add basic mySQL database infrastructure and connection.
  • Update Screenshots.
  • Update README.md
| -|Version 0.2.3 | [2020-03-17] |
  • Add further mySQL database infrastructure, including add a new entry row comprised of ID(Pri Key), Username and Password(Hashed).
  • Add new front-end form, for use to make a post request on register button, to add new user details to db.
  • Add new dependacy/module, for parseing request body.
  • Update README.md
| -|Version 0.3.0 | [2020-03-20] |
  • Big Update - Full SQL Database Integration and Support.
  • Add full user authentification to login client page, in order to access chatroom.
  • Complete the login client page registration feature, including adding new users as a row to sql db.
  • Full chatroom username and unique ID integration with sql db - all details are pulled from db.
  • Add my account section to chatroom client page, with an account overview.
  • Ability to change password in the my account section of chatroom, reflected into db also.
  • Update change username to also update account section and sql database entry.
  • Redirections: When not logged in, always redirect too the login client page. When logged in, always redirect to chatroom client page.
  • Update README.md
| -|Version 0.3.1 | [2020-03-21] |
  • Add full catch and redirection system, built up from previous implementation: Now catches any attempted unresolved urls, or unauthorised access (not logged-in), and redirects appropriately.
  • Upgrade Account section, when logged in: A further check on changing password, and also move change username to this section. Also add collapsing menu, for all options currently available.
  • Adjusted and refine code all around, as well as check and sure up comments. Adjusted so all data now come from server too.
  • Bug Fixes and Testing.
  • Update README.md
| +|Version 0.2.3 | [2020-03-17] |
  • Add further mySQL database infrastructure, including add a new entry row comprised of ID(Pri Key), Username and Password(Hashed).
  • Add new front-end form, for use to make a post request on register button, to add new user details to db.
  • Add new dependency/module, for parsing request body.
  • Update README.md
| +|Version 0.3.0 | [2020-03-20] |
  • Big Update - Full SQL Database Integration and Support.
  • Add full user authentication to login client page, in order to access chatroom.
  • Complete the login client page registration feature, including adding new users as a row to sql db.
  • Full chatroom username and unique ID integration with sql db - all details are pulled from db.
  • Add my account section to chatroom client page, with an account overview.
  • Ability to change password in the my account section of chatroom, reflected into db also.
  • Update change username to also update account section and sql database entry.
  • Redirection: When not logged in, always redirect too the login client page. When logged in, always redirect to chatroom client page.
  • Update README.md
| +|Version 0.3.1 | [2020-03-21] |
  • Add full catch and redirection system, built up from previous implementation: Now catches any attempted unresolved urls, or unauthorized access (not logged-in), and redirects appropriately.
  • Upgrade Account section, when logged in: A further check on changing password, and also move change username to this section. Also add collapsing menu, for all options currently available.
  • Adjusted and refine code all around, as well as check and sure up comments. Adjusted so all data now come from server too.
  • Bug Fixes and Testing.
  • Update README.md
| |Version 0.4.0 | [2020-03-23] |
  • Picture Day Update!
  • Redesign front-end/client-side: Updated better visuals and slightly altered chatroom layout.
  • Adjust css/html for better scaling - Now much more viewable across a range devices/screen sizes.
  • Add logout button/feature to account section in ChatRoom which disconnects from chat, logs user out (clears session data), to be returned to login page.
  • Adjusted sockets to use session data, rather than exported variables, for login status and username/id.
  • Minor routing changes.
  • Bug Fixes and Tidy-up.
  • Moves sensitive/destructive data to external json file (git-ignored), that is imported and read from.
  • Updated all screenshots in Screenshot Directory.
  • Update README.md
| |Version 0.4.1 | [2020-03-24] |
  • Minor request type changes (post -> delete/put, etc).
  • CSS/HTML minor adjustments and fine-tune.
  • Add Delete account check and action (with route and request), to delete account from db, log user out and redirect to login/register page.
  • Update README.md
| |Version 0.4.2 | [2020-03-25] |
  • Add check/feature to prevent multiple instances (or log-in) of the same account.
  • Add further error handling/catching for requests/socket-connections, preventing db changes or chatroom/account access, if user is no longer logged in.
  • Update README.md
| @@ -186,11 +186,12 @@ Below is the refined and confirmed roadmap, that has been planned for completion |Version 2.0.0 | [2020-05-18] |
  • TypeScript & Class Update - Whilst already a TypeScript project, it has been further updated to make more and better use of TypeScript features, as well as reconstructed into a more object oriented and class based design. Also sharpened up the code, fixing any mistakes, inconsistencies, or general improvements.
  • Update README.md
| |Version 2.1.0 | [2020-05-19] |
  • EJS Update - Whilst already a EJS Templated project, it has been further updated to make more and better use of ejs engine features, as well as compacting the code, fixing any mistakes/bugs, inconsistencies, and general improvements.
  • Update README.md
| |Version 2.1.1 | [2020-05-20] |
  • EJS Update - Further and general improvements.
  • Client-side Scripting restructure & tidy-up.
  • Update README.md
| -|Version 2.2.0 | [2020-05-20] |
  • Final EJS Update & Cleanup
  • Further client-side Scripting restructure & tidy-up.
  • CSS stylesheets consolidation (2=>1).
  • Comments rewriting and tidy.
  • Final checkovers and tidy up + Testing.
  • Update README.md
| +|Version 2.2.0 | [2020-05-20] |
  • Final EJS Update & Cleanup
  • Further client-side Scripting restructure & tidy-up.
  • CSS stylesheets consolidation (2=>1).
  • Comments rewriting and tidy.
  • Final check over and tidy up + Testing.
  • Update README.md
| |Version 2.2.0 | [2020-05-20] |
  • Renaming and descriptions editing.
  • Update README.md
| |Version 3.0.0 | [2021-07-29] |
  • Project-wide update, reformat and clean-up, including modules.
  • Update README.md
| -|Version 3.0.1 | [2021-07-31] |
  • Updates to session management implementation, plus a new interface.
  • Updates to database interactivity and infrastructure, creating new seperate class.
  • Update README.md
| +|Version 3.0.1 | [2021-07-31] |
  • Updates to session management implementation, plus a new interface.
  • Updates to database interactivity and infrastructure, creating new separate class.
  • Update README.md
| |Version 3.0.2 | [2021-08-01] |
  • Differentiate SocketServer further, into it's own service class, rather than a parent class of the server infrastructure.
  • Minor updates to Database class and implementation.
  • Update README.md
| +|Version 3.0.3 | [2021-08-03] |
  • Fix spelling.
  • Update README.md
|


@@ -218,7 +219,7 @@ Contributions are welcomed and, of course, **greatly appreciated**. * [Issues & Requests][issues-url] * [My Other Projects](https://github.com/tberey?tab=repositories) * [Personal Website](https://tberey.github.io/) -* [Linked In](https://uk.linkedin.com/in/thomas-berey-2a1860129) +* [Linked In](https://uk.linkedin.com/in/thomas-berey)
@@ -248,5 +249,5 @@ Contributions are welcomed and, of course, **greatly appreciated**. [issues-shield]: https://img.shields.io/github/issues/tberey/ts-node-chatroom.svg [issues-url]: https://github.com/tberey/ts-node-chatroom/issues [linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?logo=linkedin&colorB=555 -[linkedin-url]: https://uk.linkedin.com/in/thomas-berey-2a1860129 +[linkedin-url]: https://uk.linkedin.com/in/thomas-berey [project-url]: https://github.com/tberey/ts-node-chatroom/projects \ No newline at end of file diff --git a/src/Server.ts b/src/Server.ts index 2b3f9f3..449d9a3 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -54,10 +54,10 @@ export class Server extends ServerSetup { if (!results.length) res.status(401).render('index', {msg: `Incorrect Username or Password entered. Please try again.`}); else if (results.length) { - // Unhash found user's password and compare with inputted password. + // Un-hash found user's password and compare with inputted password. bcrypt.compare(password, results[0].password, (err:Error, result:boolean):Response|void => { - // bcrypt unhashing error handling. Return error and bad status. + // bcrypt un-hashing error handling. Return error and bad status. if (err) res.status(500).render('index', {msg: err}); if (err) throw err; @@ -96,7 +96,7 @@ export class Server extends ServerSetup { const password = req.body.password; const confPassword = req.body.confPassword; - // Check for missing or incorrect data, sent with request, and retunr bad response and error message. Else continue with request to register new user. + // Check for missing or incorrect data, sent with request, and return bad response and error message. Else continue with request to register new user. if (username.length > 30) res.status(422).render('index', {msg: `Username is too long (Max: 30 Characters). Enter a new username.`}); else if (password !== confPassword) res.status(422).render('index', {msg: `Your passwords entered did not match. Try again.`}); else if (!username && !password) res.status(422).render('index', {msg: `Please enter both a Username and Password, and confirm the new password.`}); @@ -145,7 +145,7 @@ export class Server extends ServerSetup { req.session.uid = `${result[0]['LAST_INSERT_ID()']}`; req.session.save((err:Error)=> {if (err) throw err}); - // Render and serve chatroom client page on successful register/login, with success repsonse. Supply ejs variables. + // Render and serve chatroom client page on successful register/login, with success response. Supply ejs variables. res.status(201).render('chatroom', { data: { username: req.session.username, @@ -184,11 +184,11 @@ export class Server extends ServerSetup { if (err) res.status(500).send(err); if (err) throw err; - // If query results found username, return bad status and message. Else continue with request and ammend username in db. + // If query results found username, return bad status and message. Else continue with request and amend username in db. if (results.length) res.status(409).send(`Username already exists. Please try another.`); else if (!(results.length)) { - // Query to edit the record, contrained by user's current username, with the new username. + // Query to edit the record, constrained by user's current username, with the new username. const query = `UPDATE ${process.env['DB_TABLE']} SET username='${newUsername}' WHERE username='${req.session.username}';`; this.db.dbConnection.query(query, (err:Error) => { @@ -200,7 +200,7 @@ export class Server extends ServerSetup { req.session.username = newUsername; req.session.save((err:Error)=> {if (err) throw err}); - // Successful request and so send back successful status, and rerender page with server message/new username. + // Successful request and so send back successful status, and render page with server message/new username. res.status(201).render('chatroom', { data: { username: req.session.username, @@ -239,7 +239,7 @@ export class Server extends ServerSetup { private putRequests():void { - // PUT Method for request made to change current password, with the new password supplied by input, and ammend in the sql db. + // PUT Method for request made to change current password, with the new password supplied by input, and amend in the sql db. this.router.put('/changePassword', (req:Request, res:Response):void => { if (!(req.session.loggedin)) return; // Error handling: do not carry out request (and break out of function), if user is not logged in. @@ -249,7 +249,7 @@ export class Server extends ServerSetup { const currentPassword = req.body.currentPassword; const confPassword = req.body.confPassword; - // Check for complete and correct request data, to carry out operation. Otherwise return a bad responseand status, with message. + // Check for complete and correct request data, to carry out operation. Otherwise return a bad response and status, with message. if (!newPassword || !currentPassword) res.status(422).send(`Please enter both your current and new password.`); else if (newPassword !== confPassword) res.status(422).send(`The new passwords you entered do not match each other. Please try again.`); else if (newPassword && currentPassword) { @@ -265,7 +265,7 @@ export class Server extends ServerSetup { // Check returned hashed db password matches inputted current password. bcrypt.compare(currentPassword, results[0].password, (err:Error, result:boolean) => { - // bcrypt unhashing error handling. Return error and bad status. + // bcrypt un-hashing error handling. Return error and bad status. if (err) res.status(500).send(err); if (err) throw err; diff --git a/src/services/Rollbar.ts b/src/services/Rollbar.ts index 7bca531..2e792b0 100644 --- a/src/services/Rollbar.ts +++ b/src/services/Rollbar.ts @@ -17,7 +17,7 @@ export class Rollbar { }); this.rollbarInfo(`Rollbar Successfully Configured with Application: ${appName}.`); - this.txtLogger.writeToLogFile('Initialised Logging: Rollbar Setup.'); + this.txtLogger.writeToLogFile('Initialized Logging: Rollbar Setup.'); } public rollbarInfo(info:Error | string): void { diff --git a/src/services/SocketsServer.ts b/src/services/SocketsServer.ts index ffff1b8..838b945 100644 --- a/src/services/SocketsServer.ts +++ b/src/services/SocketsServer.ts @@ -54,7 +54,7 @@ export class SocketsServer { // Create a new user, using stored request session properties. const user:IUser = { uniqueID: socket.request.session.uid, name: socket.request.session.username }; - // Add newly connected user to set, and emit to all clients to clear exisiting user list to replace with updated list. Send server update message in chat. + // Add newly connected user to set, and emit to all clients to clear existing user list to replace with updated list. Send server update message in chat. userSet.add(user); let serverMsg = `

Server says:
New messenger arrived, welcome '${user.name}'! diff --git a/src/tests/TestServer.ts b/src/tests/TestServer.ts new file mode 100644 index 0000000..4ade21d --- /dev/null +++ b/src/tests/TestServer.ts @@ -0,0 +1,35 @@ +import http from 'http'; +import express, { Express, Router, Request, Response } from 'express'; + +export class TestServer { + + private server: http.Server; + private router: Router; + public app: Express; + + public constructor(port = 3030, hostname = '127.0.0.1') { + this.router = express.Router(); + this.app = express(); + this.server = new http.Server(this.app); + + this.app.use("/", this.router); + this.server.listen(port, hostname); + this.testRoutes(); + } + + testRoutes(): void { + this.router.get('/test', (req:Request, res:Response) => res.status(200).send(req.body)); + + this.router.post('/test', (req:Request, res:Response) => { + res.status(200).send(req.body); + }); + + this.router.put('/test', (req:Request, res:Response) => { + res.status(200).send(req.body); + }); + + this.router.delete('/test', (req:Request, res:Response) => { + res.status(200).send(req.body); + }); + } +} \ No newline at end of file diff --git a/src/tests/deployment.test.ts b/src/tests/deployment.test.ts new file mode 100644 index 0000000..10d8d6d --- /dev/null +++ b/src/tests/deployment.test.ts @@ -0,0 +1,21 @@ +import { TestServer } from './TestServer'; +import chai from 'chai'; +import chaiHttp from 'chai-http'; +import 'mocha'; + +chai.use(chaiHttp); +const app = (new TestServer(8000,'localhost')).app; + +describe('[API] GET Check', () => { + it('Should return a 200 status', () => { + return chai.request(app).get('/test').then(res => chai.expect(res.status).to.equal(200)); + }); +}); + +describe('[API] POST Check', () => { + it('Should return a 200 status', () => { + return chai.request(app).post('/test').send({test: "testing"}).then(res => { + chai.expect(res.status).to.equal(200); + }); + }); +}); \ No newline at end of file diff --git a/src/tests/spec.test.ts b/src/tests/spec.test.ts new file mode 100644 index 0000000..be9e48a --- /dev/null +++ b/src/tests/spec.test.ts @@ -0,0 +1,29 @@ +import { Server } from '../Server'; +import chai from 'chai'; +import chaiHttp from 'chai-http'; +import 'mocha'; + +chai.use(chaiHttp); + +const app = (new Server('8000','localhost')).appAccessor; +//if (!app) process.exit(1); + +describe('[API] Health Check', () => { + it('Should return a 200 status', async (done) => { + return await chai.request(app).get('/test') + .then(res => { + chai.expect(res.status).to.equal(404); + done(); + }) + }) +}); + +describe('[AWS] GET /listBuckets', () => { + it('Should return a 200 status', async (done) => { + return await chai.request(app).get('/test') + .then(res => { + chai.expect(res.status).to.equal(404); + done(); + }); + }) +}); \ No newline at end of file diff --git a/views/partials/chatScript.ejs b/views/partials/chatScript.ejs index e0a745c..ffdcd44 100644 --- a/views/partials/chatScript.ejs +++ b/views/partials/chatScript.ejs @@ -69,14 +69,14 @@ // Listen for the user list items to be emitted by server on connection, and append to html. socket.on('userListItem', (data) => userList.append(data)); - // Listen for delete list signal to clear userl list in the html, in prep for a new list emitted. Append received data to html, and scroll view. + // Listen for delete list signal to clear user-list in the html, in prep for a new list emitted. Append received data to html, and scroll view. socket.on('deleteList', (data) => { userList.html(''); if (data) chatroom.append(data); $('#chatroom').scrollTop($('#chatroom').prop('scrollHeight')); }); - // Listen the full message list being retuned. Append any received messages to DOM, and auto-scroll to bottom of element. + // Listen the full message list being returned. Append any received messages to DOM, and auto-scroll to bottom of element. socket.on('msgSetItem', (data) => { chatroom.append(data); $("#chatroom").animate({scrollTop:$("#chatroom")[0].scrollHeight}, 80); From 6c845d5c22e4d3779baa55ca6c688f4dc9cb3422 Mon Sep 17 00:00:00 2001 From: Tom Berey Date: Wed, 4 Aug 2021 17:48:34 +0100 Subject: [PATCH 4/5] Ver:3.0.3--Minor-Updates --- README.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 98ccbf0..8301159 100644 --- a/README.md +++ b/README.md @@ -127,9 +127,16 @@ For help or guidance in downloading and running the application, see the followi ## Usage -| Endpoint | Action/Desc. | Full URI (hosted locally, for some port; e.g.: 3000) | -|:---|:---|:---| -|

  • "/"
| Homepage:
The client-side landing page. |
  • "http://localhost:3000/"
| +| Endpoint | Action/Desc. | Full URI (hosted locally, on some port; e.g.: 3000) | Request Type | +|:---|:---|:---|:---| +|
  • "/"
| Home Page:
The client-side landing page. Login or Register. |
  • "http://localhost:3000/"
| GET | +|
  • "/chat"
| Chatroom:
If logged in, this is the url for the chatroom. if not logged in, redirects to home page. |
  • "http://localhost:3000/chat"
| GET | +|
  • "/login"
| Post request to login a user, with supplied credentials. If successful, redirects to chatroom. |
  • "http://localhost:3000/login"
| POST | +|
  • "/register"
| Post request to register a user, with supplied credentials. |
  • "http://localhost:3000/register"
| POST | +|
  • "/changeUsername"
| Post request to update a logged in user's username. |
  • "http://localhost:3000/changeUsername"
| POST | +|
  • "/logout"
| Post request to log out a user and redirect to home page. |
  • "http://localhost:3000/logout"
| POST | +|
  • "/changePassword"
| Put request to update a logged in user's password. |
  • "http://localhost:3000/changePassword"
| PUT | +|
  • "/delete"
| Delete request to delete and hence log out a user, and redirect to home page. Hard delete of account. |
  • "http://localhost:3000/delete"
| DELETE |
@@ -192,6 +199,7 @@ Below is the refined and confirmed roadmap, that has been planned for completion |Version 3.0.1 | [2021-07-31] |
  • Updates to session management implementation, plus a new interface.
  • Updates to database interactivity and infrastructure, creating new separate class.
  • Update README.md
| |Version 3.0.2 | [2021-08-01] |
  • Differentiate SocketServer further, into it's own service class, rather than a parent class of the server infrastructure.
  • Minor updates to Database class and implementation.
  • Update README.md
| |Version 3.0.3 | [2021-08-03] |
  • Fix spelling.
  • Update README.md
| +|Version 3.0.3 | [2021-08-04] |
  • Update README.md
|


From b43ac4f218307b656743ef20b72879de5d1aa631 Mon Sep 17 00:00:00 2001 From: Tom Berey Date: Wed, 4 Aug 2021 17:48:57 +0100 Subject: [PATCH 5/5] Ver:3.0.4--Minor-Updates --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8301159..d86c5e8 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ Below is the refined and confirmed roadmap, that has been planned for completion |Version 3.0.1 | [2021-07-31] |
  • Updates to session management implementation, plus a new interface.
  • Updates to database interactivity and infrastructure, creating new separate class.
  • Update README.md
| |Version 3.0.2 | [2021-08-01] |
  • Differentiate SocketServer further, into it's own service class, rather than a parent class of the server infrastructure.
  • Minor updates to Database class and implementation.
  • Update README.md
| |Version 3.0.3 | [2021-08-03] |
  • Fix spelling.
  • Update README.md
| -|Version 3.0.3 | [2021-08-04] |
  • Update README.md
| +|Version 3.0.4 | [2021-08-04] |
  • Update README.md
|