*: switch sessionId to server-side

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2023-09-28 21:19:58 -04:00
parent 67826bb20d
commit 380ec821b1
Signed by: vbatts
GPG key ID: E30EFAA812C6E5ED
6 changed files with 2755 additions and 34 deletions

22
app.js
View file

@ -1,13 +1,15 @@
const express = require('express'); const express = require('express');
const session = require('express-session');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const morgan = require('morgan'); const morgan = require('morgan');
const bodyParser = require('body-parser'); const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose(); const sqlite3 = require('sqlite3').verbose();
const bole = require('bole'); const bole = require('bole');
const log = bole('app');
const config = require('./config'); const config = require('./config');
const log = bole('app');
const app = express(); const app = express();
// Create an SQLite database and initialize tables // Create an SQLite database and initialize tables
@ -43,6 +45,11 @@ var accessLogStream = fs.createWriteStream(
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(morgan("combined", { stream: accessLogStream })); app.use(morgan("combined", { stream: accessLogStream }));
app.use(session({
resave: false,
saveUninitialized: false,
secret: config.session_token,
}));
var animals; var animals;
// check and load animals into redis // check and load animals into redis
@ -77,12 +84,25 @@ try {
// Serve the HTML file // Serve the HTML file
app.get("/", (req, res) => { app.get("/", (req, res) => {
if (typeof req.session.cookie.expires == "undefined") {
var hour = 3600000;
req.session.cookie.expires = new Date(Date.now() + hour);
req.session.cookie.maxAge = hour;
}
res.sendFile(__dirname + "/index.html"); res.sendFile(__dirname + "/index.html");
}); });
app.get("/asset/frontend.js", (req, res) => { app.get("/asset/frontend.js", (req, res) => {
res.sendFile(__dirname + "/asset/frontend.js"); res.sendFile(__dirname + "/asset/frontend.js");
}); });
app.get("/newSession", (req, res) => {
// XXX
log.info(req.session);
req.session.regenerate();
log.info(req.session);
});
// Route to get a random animal name // Route to get a random animal name
app.get("/getNextAnimal", async (req, res) => { app.get("/getNextAnimal", async (req, res) => {
try { try {

View file

@ -2,14 +2,6 @@
let sessionStartTime; let sessionStartTime;
let lastButtonClickTime; let lastButtonClickTime;
// Function to generate a random session ID
function generateSessionId() {
return (
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15)
);
}
// Function to fetch a random animal name from the server // Function to fetch a random animal name from the server
async function getNextAnimal() { async function getNextAnimal() {
try { try {
@ -28,17 +20,20 @@ function getSessionId() {
"$1", "$1",
); );
if (!sessionId) { if (!sessionId) {
const newSessionId = generateSessionId(); return newSession();
document.cookie = `sessionId=${newSessionId}`;
return newSessionId;
} }
return sessionId; return sessionId;
} }
function clearSessionId() { async function newSession() {
const newSessionId = generateSessionId();
document.cookie = `sessionId=${newSessionId}`;
setSessionStartTime(); setSessionStartTime();
try {
const response = await fetch("/newSession");
const data = await response.json();
document.getElementById("animal-name").textContent = data.animalName;
} catch (error) {
console.error("Error fetching data:", error);
}
getSessionId(); getSessionId();
} }
@ -56,20 +51,6 @@ function displayTimeDifference() {
} }
} }
// Add click event listeners to the buttons
document.getElementById("isCritterButton").addEventListener("click", () => {
recordButtonClick("is critter", getSessionId());
});
document.getElementById("isNotCritterButton").addEventListener("click", () => {
recordButtonClick("is not critter", getSessionId());
});
document.getElementById("startOverButton").addEventListener("click", () => {
clearSessionId();
getNextAnimal();
});
// Function to record button clicks on the server // Function to record button clicks on the server
async function recordButtonClick(buttonName, sessionId) { async function recordButtonClick(buttonName, sessionId) {
try { try {
@ -103,6 +84,20 @@ async function recordButtonClick(buttonName, sessionId) {
} }
} }
// Add click event listeners to the buttons
document.getElementById("isCritterButton").addEventListener("click", () => {
recordButtonClick("is critter", getSessionId());
});
document.getElementById("isNotCritterButton").addEventListener("click", () => {
recordButtonClick("is not critter", getSessionId());
});
document.getElementById("startOverButton").addEventListener("click", () => {
newSession();
getNextAnimal();
});
// Initial random animal load and session start time // Initial random animal load and session start time
getNextAnimal(); getNextAnimal();
setSessionStartTime(); setSessionStartTime();

View file

@ -1,5 +1,5 @@
var config = module.exports; const config = module.exports;
var PRODUCTION = process.env.NODE_ENV === 'production'; const PRODUCTION = process.env.NODE_ENV === 'production';
const bole = require('bole'); const bole = require('bole');
config.express = { config.express = {
@ -9,9 +9,11 @@ config.express = {
if (PRODUCTION) { if (PRODUCTION) {
config.express.ip = '0.0.0.0'; config.express.ip = '0.0.0.0';
config.db_path = "db/results.db"; config.db_path = 'db/results.db';
config.session_token = process.env.SESSION_TOKEN;
bole.output({ level: 'info', stream: process.stdout }) bole.output({ level: 'info', stream: process.stdout })
} else { } else {
config.db_path = ":memory:"; config.db_path = ':memory:';
config.session_token = 'cat bag';
bole.output({ level: 'debug', stream: process.stdout }) bole.output({ level: 'debug', stream: process.stdout })
} }

2702
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -18,11 +18,13 @@
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"bole": "^5.0.7", "bole": "^5.0.7",
"express": "^4.18.2", "express": "^4.18.2",
"express-session": "^1.17.3",
"morgan": "^1.10.0", "morgan": "^1.10.0",
"sqlite3": "^5.1.6" "sqlite3": "^5.1.6"
}, },
"devDependencies": { "devDependencies": {
"jest": "^29.7.0", "jest": "^29.7.0",
"standard": "^17.1.0",
"supertest": "^6.3.3" "supertest": "^6.3.3"
} }
} }

View file

@ -1,6 +1,6 @@
const bole = require('bole');
const config = require('./config'); const config = require('./config');
const app = require('./app'); const app = require('./app');
const bole = require('bole');
const log = bole('server'); const log = bole('server');
app.listen(config.express.port, config.express.ip, function(error) { app.listen(config.express.port, config.express.ip, function(error) {