5 Commits

Author SHA1 Message Date
e4c038c940 Added login and sessiontoken 2025-10-02 22:27:07 +02:00
2bae9db84f added creation of default admin user and login. TODO authenticate with session token 2025-10-02 11:23:15 +02:00
f99aee302a added express js 2025-10-02 10:14:53 +02:00
f1d5bead86 Update readme 2025-09-29 17:16:33 +02:00
216f977165 Add Readme 2025-09-29 17:10:44 +02:00
10 changed files with 1543 additions and 105 deletions

13
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,13 @@
{
"rest-client.environmentVariables": {
"$shared": {},
"local": {
"host": "localhost",
"port": "12345"
},
"docker": {
"host": "localhost",
"port": "11001"
}
}
}

View File

@@ -14,6 +14,7 @@ FROM node:${NODE_VERSION}-alpine
WORKDIR /app WORKDIR /app
COPY --from=builder /app/node_modules node_modules/ COPY --from=builder /app/node_modules node_modules/
COPY --from=builder /app/index.js . COPY --from=builder /app/index.js .
COPY --from=builder /app/src src/
USER node USER node
EXPOSE 12345 EXPOSE 12345
ENV NODE_ENV=production ENV NODE_ENV=production

32
Readme.md Normal file
View File

@@ -0,0 +1,32 @@
# Jeopardy Server
Der Server für Jeopardy
## Developing
Zum entwickeln am besten `docker compose` nutzen.
```sh
npm run docker-build
```
Dann im Jeopardy Projekt die `docker-compose.yml` starten. Eventuell muss dort die `docker-compose.yml` und das `.env.local` angepasst werden, sollte aber eigentlich alles so stimmen.
Ansonsten kann man auch mit `npm run dev` entwickeln.
## Build Production
1. Versionsnummer in `package.json` updaten
2. commit erstellen und mit Versionsnummer taggen
3. push des commits **und der tags**
4. Auf Server connecten
```sh
sudo su
cd /opt/jeopardy/Jeopardy-Server
git fetch --tags
git checkout <versionsnummer>
docker build -t jeopardy .
docker tag jeopardyserver:latest jeopardyserver:<versionsnummer>
cd ..
docker compose up -d
```

130
index.js
View File

@@ -1,111 +1,31 @@
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 cookieParser from "cookie-parser";
import { initWebsocket } from "./src/websocket.js";
import { initAuth } from "./src/auth.js";
import { close as closeDbConnection, initDbConnection, db } from "./src/db.js";
const app = express();
const appWs = expressWs(app);
const port = 12345;
let hostConnection; process.on('exit', function() {
let displayConnection; console.log('Shutting down...');
console.log('Closing db connection...');
const wss = new WebSocketServer({ closeDbConnection();
port: 12345,
}, () => {
console.log("Websocket Server started\nListening on Port 12345")
}); });
wss.on('connection', (ws) => { app.use(morgan(process.env.production ? 'common' : 'dev'));
console.log("Trying to connect"); app.use(express.json());
ws.on('error', console.error); app.use(cookieParser());
ws.on('message', (data) => { await initDbConnection();
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();
}
})
// 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");
}
}

1222
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,6 +11,16 @@
"docker-build": "docker build -t jeopardyserver ." "docker-build": "docker build -t jeopardyserver ."
}, },
"dependencies": { "dependencies": {
"@types/express": "^5.0.3",
"cookie-parser": "^1.4.7",
"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" "ws": "^8.18.3"
},
"devDependencies": {
"@types/node": "^24.6.0"
} }
} }

10
requests/test.http Normal file
View File

@@ -0,0 +1,10 @@
@url = http://{{host}}:{{port}}
POST {{url}}/auth/login HTTP/1.1
content-type: application/json
{
"username": "jonas",
"password": "kappa"
}

106
src/auth.js Normal file
View File

@@ -0,0 +1,106 @@
import { createHash, pbkdf2Sync, randomBytes } from "node:crypto";
let db;
let users;
export function initAuth(app, db) {
app.use(checkSessionToken);
users = db.collection('users');
app.post('/auth/login', loginUser);
}
async function checkSessionToken(req, res, next) {
if (req.path.startsWith("/auth/")) {
next();
return;
}
const token = req.cookies.jeopardytoken;
let user = await users.findOne({sessiontoken: token});
if (user === null) {
res.sendStatus(401);
return;
}
req.user = {
role: user.role,
username: user.username
}
next();
}
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.status(200).send(username);
} 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
src/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();
}

103
src/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();
}
})
});
}