Compare commits

..

2 Commits

7 changed files with 1447 additions and 105 deletions

81
auth.js Normal file
View File

@@ -0,0 +1,81 @@
import { createHash, pbkdf2Sync, randomBytes } from "node:crypto";
let db;
let users;
export function initAuth(app, db) {
users = db.collection('users');
app.post('/auth/login', loginUser);
}
async function loginUser(req, res) {
const username = req.body.username;
const password = req.body.password;
let userCount = await users.estimatedDocumentCount();
let sessiontoken = null;
if (userCount <= 0) {
// create first user
sessiontoken = await createUser(username, password, 'admin');
} else {
// authenticate user
sessiontoken = await authenticateUser(username, password);
}
if (sessiontoken !== null) {
const expires = new Date();
expires.setDate(expires.getDate() + 1);
res.cookie('jeopardytoken', sessiontoken, {
maxAge: 1e3 * 60 * 60 * 24
})
res.sendStatus(200);
} else {
res.sendStatus(403);
}
}
async function createUser(username, password, role) {
const salt = randomBytes(128).toString('base64');
const iterations = Math.floor(Math.random() * 5000) + 5000;
const hash = generateHash(password, salt, iterations);
const sessiontoken = generateSessionToken();
await users.insertOne({
username,
role,
salt,
iterations,
hash,
sessiontoken
});
return sessiontoken;
}
async function authenticateUser(username, password) {
let foundUser = await users.findOne({username});
if (foundUser === null) return null;
const hash = generateHash(password, foundUser.salt, foundUser.iterations);
if (hash === foundUser.hash) {
const sessiontoken = generateSessionToken();
await users.updateOne({_id: foundUser._id}, {$set: {
sessiontoken
}});
return sessiontoken;
}
return null;
}
function generateSessionToken() {
return randomBytes(128).toString('base64');
}
function generateHash(password, salt, iterations) {
return pbkdf2Sync(password, salt, iterations, 128, 'sha512').toString('hex');
}

21
db.js Normal file
View File

@@ -0,0 +1,21 @@
import { MongoClient } from "mongodb";
let client;
const dbName = `jeopardy`;
/**
* @type {Db}
*/
export let db;
export async function initDbConnection() {
client = new MongoClient(`mongodb://${process.env.JEOPARDYSERVER_MONGO_USERNAME}:${process.env.JEOPARDYSERVER_MONGO_PASSWORD}@${process.env.JEOPARDYSERVER_MONGO_URL}/`);
await client.connect();
console.log('Connected successfully to mongodb');
db = client.db(dbName);
}
export function close() {
client.close();
}

128
index.js
View File

@@ -1,111 +1,29 @@
import WebSocket, { WebSocketServer } from 'ws';
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import expressWs from "express-ws";
import morgan from "morgan";
import { initWebsocket } from "./websocket.js";
import { initAuth } from "./auth.js";
import { close as closeDbConnection, initDbConnection, db } from "./db.js";
const app = express();
const appWs = expressWs(app);
const port = 12345;
let hostConnection;
let displayConnection;
const wss = new WebSocketServer({
port: 12345,
}, () => {
console.log("Websocket Server started\nListening on Port 12345")
process.on('exit', function() {
console.log('Shutting down...');
console.log('Closing db connection...');
closeDbConnection();
});
wss.on('connection', (ws) => {
console.log("Trying to connect");
ws.on('error', console.error);
app.use(morgan(process.env.production ? 'common' : 'dev'));
app.use(express.json());
ws.on('message', (data) => {
if (ws == hostConnection || ws == displayConnection) return;
console.log('received: %s', data);
if (data == "HOST") {
if (hostConnection === undefined) {
hostConnection = ws;
initHostConnection();
}
else
{
ws.send("ERROR HOST");
ws.close();
}
} else if (data == "DISPLAY") {
if (displayConnection === undefined) {
displayConnection = ws;
initDisplayConnection();
}
else
{
ws.send("ERROR DISPLAY");
ws.close();
}
}
else
{
ws.send("ERROR MESSAGE");
ws.close();
}
})
await initDbConnection();
// ws.send('Connected to server');
initAuth(app, db);
initWebsocket(app);
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
function initHostConnection() {
console.log("Initialize Host connection...");
hostConnection.on('message', (data) => {
console.log("[HOST] " + data);
if (displayConnection) {
displayConnection.send("" + data);
}
});
hostConnection.on('error', (data) => {
console.error("[HOST] " + data);
hostConnection = undefined;
if (displayConnection) {
displayConnection.send("HOST-DISCONNECTED");
}
});
hostConnection.on('close', (code, reason) => {
console.error("[HOST] " + code + " " + reason);
hostConnection = undefined;
if (displayConnection) {
displayConnection.send("HOST-DISCONNECTED");
}
});
hostConnection.send("HOST");
if (displayConnection) {
displayConnection.send("HOST-CONNECTED");
hostConnection.send("DISPLAY-CONNECTED");
}
}
function initDisplayConnection() {
console.log("Initialize Display connection...");
displayConnection.on('message', (data) => {
console.log("[DISPLAY] " + data);
});
displayConnection.on('error', (data) => {
console.error("[DISPLAY] " + data);
displayConnection = undefined;
if (hostConnection) {
hostConnection.send("DISPLAY-DISCONNECTED");
}
});
displayConnection.on('close', (code, reason) => {
console.error("[DISPLAY] " + code + " " + reason);
displayConnection = undefined;
if (hostConnection) {
hostConnection.send("DISPLAY-DISCONNECTED");
}
});
displayConnection.send("DISPLAY");
if (hostConnection) {
hostConnection.send("DISPLAY-CONNECTED");
displayConnection.send("HOST-CONNECTED");
}
}

1202
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,6 +11,15 @@
"docker-build": "docker build -t jeopardyserver ."
},
"dependencies": {
"@types/express": "^5.0.3",
"dotenv": "^17.2.3",
"express": "^5.1.0",
"express-ws": "^5.0.2",
"mongodb": "^6.20.0",
"morgan": "^1.10.1",
"ws": "^8.18.3"
},
"devDependencies": {
"@types/node": "^24.6.0"
}
}

8
requests/test.http Normal file
View File

@@ -0,0 +1,8 @@
POST http://localhost:12345/auth/login HTTP/1.1
content-type: application/json
{
"username": "jonas",
"password": "kappa"
}

103
websocket.js Normal file
View File

@@ -0,0 +1,103 @@
let hostConnection;
let displayConnection;
function initHostConnection() {
console.log("Initialize Host connection...");
hostConnection.on('message', (data) => {
console.log("[HOST] " + data);
if (displayConnection) {
displayConnection.send("" + data);
}
});
hostConnection.on('error', (data) => {
console.error("[HOST] " + data);
hostConnection = undefined;
if (displayConnection) {
displayConnection.send("HOST-DISCONNECTED");
}
});
hostConnection.on('close', (code, reason) => {
console.error("[HOST] " + code + " " + reason);
hostConnection = undefined;
if (displayConnection) {
displayConnection.send("HOST-DISCONNECTED");
}
});
hostConnection.send("HOST");
if (displayConnection) {
displayConnection.send("HOST-CONNECTED");
hostConnection.send("DISPLAY-CONNECTED");
}
}
function initDisplayConnection() {
console.log("Initialize Display connection...");
displayConnection.on('message', (data) => {
console.log("[DISPLAY] " + data);
});
displayConnection.on('error', (data) => {
console.error("[DISPLAY] " + data);
displayConnection = undefined;
if (hostConnection) {
hostConnection.send("DISPLAY-DISCONNECTED");
}
});
displayConnection.on('close', (code, reason) => {
console.error("[DISPLAY] " + code + " " + reason);
displayConnection = undefined;
if (hostConnection) {
hostConnection.send("DISPLAY-DISCONNECTED");
}
});
displayConnection.send("DISPLAY");
if (hostConnection) {
hostConnection.send("DISPLAY-CONNECTED");
displayConnection.send("HOST-CONNECTED");
}
}
export function initWebsocket(app) {
app.ws("/websocket", (ws, req) => {
console.log("Trying to connect");
ws.on('error', console.error);
ws.on('message', (data) => {
if (ws == hostConnection || ws == displayConnection) return;
console.log('received: %s', data);
if (data == "HOST") {
if (hostConnection === undefined) {
hostConnection = ws;
initHostConnection();
}
else
{
ws.send("ERROR HOST");
ws.close();
}
} else if (data == "DISPLAY") {
if (displayConnection === undefined) {
displayConnection = ws;
initDisplayConnection();
}
else
{
ws.send("ERROR DISPLAY");
ws.close();
}
}
else
{
ws.send("ERROR MESSAGE");
ws.close();
}
})
});
}