20 Commits
1.0.1 ... 2.0.0

Author SHA1 Message Date
284615573f Release 2.0.0
Reworked default points
2026-01-03 00:37:33 +01:00
ba96584300 Added Editing of Questions 2026-01-02 18:01:02 +01:00
832ff99a7b Added rename of Game, Wall and Category 2026-01-02 12:35:59 +01:00
1940d67c37 Added fetching of categories and questions 2026-01-02 02:59:57 +01:00
4153fcd8d5 changed pw in auth 2026-01-01 13:27:21 +01:00
163fccb9b2 Added wall creation, deletion and fetching 2026-01-01 13:26:27 +01:00
cd72390f42 Added game creation and deletion 2025-12-28 12:51:15 +01:00
b923785c9f Added deletion and renaming of files and deletion of directories 2025-12-23 17:42:54 +01:00
08f8cc7fc3 Added creation and fetching of directories and files 2025-12-23 12:25:55 +01:00
273314739f Added File uploads and fetching of said files 2025-12-22 13:03:14 +01:00
ba6d8eeffc New release 1.0.4 2025-10-07 23:06:54 +02:00
4ccdbfc8a4 Added Logout, some fixes 2025-10-07 23:06:32 +02:00
34696a1fc8 Added user management 2025-10-04 13:40:30 +02:00
a197d9bd3b Bump version to 1.0.2 2025-10-03 11:41:58 +02:00
91cdc9e08a Updated login 2025-10-03 11:41:30 +02:00
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
19 changed files with 3239 additions and 111 deletions

6
.gitignore vendored
View File

@@ -138,3 +138,9 @@ dist
# Vite logs files # Vite logs files
vite.config.js.timestamp-* vite.config.js.timestamp-*
vite.config.ts.timestamp-* vite.config.ts.timestamp-*
# user files
/responses
/data

7
.prettierrc Normal file
View File

@@ -0,0 +1,7 @@
{
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true,
"endOfLine": "lf"
}

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

@@ -11,10 +11,14 @@ COPY . .
RUN npm prune --production RUN npm prune --production
FROM node:${NODE_VERSION}-alpine FROM node:${NODE_VERSION}-alpine
RUN mkdir -p /data
RUN chown node /data
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
ENV JEOPARDY_CDN_DATA_PATH=/data
CMD [ "node", "."] CMD [ "node", "."]

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 jeopardyserver .
docker tag jeopardyserver:latest jeopardyserver:<versionsnummer>
cd ..
docker compose up -d
```

138
index.js
View File

@@ -1,111 +1,33 @@
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 cors from 'cors';
import { initWebsocket } from './src/websocket.js';
import { initAuth } from './src/auth.js';
import { initDbConnection, db } from './src/db.js';
import { initUsers } from './src/user.js';
import { initCdn } from './src/cdn.js';
import { initGames } from './src/games.js';
const app = express();
const appWs = expressWs(app);
const port = 12345;
let hostConnection; app.use(cors({ credentials: true, origin: process.env.JEOPARDY_URL }));
let displayConnection; app.use(morgan(process.env.production ? 'common' : 'dev'));
app.use(express.json());
app.use(cookieParser());
const wss = new WebSocketServer({ await initDbConnection();
port: 12345,
}, () => { initAuth(app, db);
console.log("Websocket Server started\nListening on Port 12345") initUsers(app, db);
initWebsocket(app);
initCdn(app, db);
initGames(app, db);
app.listen(port, () => {
console.log(`Listening on port ${port}`);
}); });
wss.on('connection', (ws) => {
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();
}
})
// ws.send('Connected to server');
});
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");
}
}

1439
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "jeopardyserver", "name": "jeopardyserver",
"version": "1.0.1", "version": "2.0.0",
"description": "", "description": "",
"license": "ISC", "license": "ISC",
"author": "", "author": "",
@@ -11,6 +11,19 @@
"docker-build": "docker build -t jeopardyserver ." "docker-build": "docker build -t jeopardyserver ."
}, },
"dependencies": { "dependencies": {
"@types/express": "^5.0.3",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"dotenv": "^17.2.3",
"express": "^5.1.0",
"express-ws": "^5.0.2",
"mongodb": "^6.20.0",
"morgan": "^1.10.1",
"multer": "^2.0.2",
"ws": "^8.18.3" "ws": "^8.18.3"
},
"devDependencies": {
"@types/node": "^24.6.0",
"prettier": "^3.7.4"
} }
} }

14
requests/auth.http Normal file
View File

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

55
requests/user.http Normal file
View File

@@ -0,0 +1,55 @@
@url = http://{{host}}:{{port}}
PUT {{url}}/admin/user HTTP/1.1
Content-Type: application/json
{
"username": "Paula"
}
###
GET {{url}}/admin/user/list HTTP/1.1
###
POST {{url}}/admin/user/resetpw HTTP/1.1
Content-Type: application/json
{
"userid": "68e1058faf78b3aabbdfe8dc"
}
###
GET {{url}}/admin/roles HTTP/1.1
###
POST {{url}}/admin/user/changerole HTTP/1.1
Content-Type: application/json
{
"userid": "68e0efc6e4ac740114d8fc9d",
"role": "default"
}
###
POST {{url}}/user/changepw HTTP/1.1
Content-Type: application/json
{
"old": "DkgnWspm4To2ww==",
"new": "Kolata"
}
###
DELETE {{url}}/admin/user HTTP/1.1
Content-Type: application/json
{
"userid": "68e0f66a7b5795e3704501cf"
}

132
src/auth.js Normal file
View File

@@ -0,0 +1,132 @@
import { createUser, generateHash, updateSessionToken } from './userHelper.js';
let db;
let users;
export function initAuth(app, db) {
app.use(checkSessionToken);
app.use('/admin', checkAuthorization('admin'));
users = db.collection('users');
app.get('/auth', getUserInfo);
app.post('/auth/login', loginUser);
}
async function getUserInfo(req, res) {
// const sessiontoken = await updateSessionToken(users, req.user._id);
// setTokenCookie(res, sessiontoken);
res.status(200).send({
username: req.user.username,
role: req.user.role,
_id: req.user._id,
});
}
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,
_id: user._id,
};
next();
}
function checkAuthorization(role) {
return (req, res, next) => {
if (req.user === undefined) {
res.status(403).send();
return;
}
if (req.user.role === role) {
next();
} else {
res.status(403).send();
}
};
}
async function loginUser(req, res) {
const username = req.body.username;
const password = req.body.password;
let userCount = await users.estimatedDocumentCount();
let userobj = null;
if (userCount <= 0) {
// create first user
userobj = await createUser(users, username, password, 'admin', true);
} else {
// authenticate user
userobj = await authenticateUser(username, password);
}
if (userobj !== null) {
setTokenCookie(res, userobj.sessiontoken);
res.status(200).send({
username: userobj.username,
role: userobj.role,
_id: userobj._id,
});
} else {
res.sendStatus(403);
}
}
export async function authenticateUser(
username,
password,
updateSession = true,
) {
let foundUser = await users.findOne({ username });
if (foundUser === null) return null;
const hash = generateHash(password, foundUser.salt, foundUser.iterations);
if (hash === foundUser.hash) {
if (updateSession) {
let sessiontoken = await updateSessionToken(users, foundUser._id);
return {
sessiontoken,
username,
role: foundUser.role,
_id: foundUser._id,
};
} else {
return {
sessiontoken: foundUser.sessiontoken,
username,
role: foundUser.role,
_id: foundUser._id,
};
}
}
return null;
}
function setTokenCookie(res, sessiontoken) {
const expires = new Date();
expires.setDate(expires.getDate() + 1);
res.cookie('jeopardytoken', sessiontoken, {
maxAge: 1e3 * 60 * 60 * 24 * 7,
path: '/',
});
}

328
src/cdn.js Normal file
View File

@@ -0,0 +1,328 @@
import { rmSync } from 'fs';
import { copyFile, mkdir, readdir, rm } from 'fs/promises';
import { Collection, Db, ObjectId } from 'mongodb';
import multer from 'multer';
const dataPath = process.env.JEOPARDY_CDN_DATA_PATH;
const upload = multer({ dest: dataPath });
/**
* @type {Collection}
*/
let ressources;
function buildPath(userid, path) {
return `${dataPath}/${userid}${path.length === '/' ? '' : path}`;
}
function ressourcePath(res) {
return `${res.fullpath}/${res.filename}`;
}
/**
*
* @param {*} app
* @param {Db} db
*/
export function initCdn(app, db) {
ressources = db.collection('ressources');
app.post('/upload', upload.single('file'), uploadFile);
app.get('/cdn/:userid/:resid', fetchFile);
app.put('/cdn/:userid/:resid', renameFile);
app.delete('/cdn/:userid/:resid', deleteFile);
app.get('/ressource', fetchRessource);
app.post('/directory', fetchDirectory);
app.put('/directory', addDirectory);
app.delete('/directory', deleteDirectory);
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
* @param {import('express').NextFunction} next
*/
function uploadFile(req, res, next) {
console.log(req.file, req.body);
/**
* @type {string | undefined}
*/
const path = req.body.path;
if (path !== undefined && path.startsWith('/') && !path.includes('.')) {
let destinationPath = buildPath(req.user._id, req.body.path);
mkdir(destinationPath, {
recursive: true,
})
.then(() => {
return copyFile(
req.file.path,
`${destinationPath}/${req.file.filename}`,
);
})
.then(async () => {
rmSync(req.file.path);
await ressources.insertOne({
fullpath: destinationPath,
path: path,
user: req.user._id,
mimetype: req.file.mimetype,
name: req.file.originalname,
filename: req.file.filename,
});
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
rmSync(req.file.path);
res.sendStatus(500);
});
} else {
rmSync(req.file.path);
res.sendStatus(400);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchRessource(req, res) {
if (req.query.id === undefined || req.query.id.length <= 0) {
res.sendStatus(400);
return;
}
const id = new ObjectId(req.query.id);
ressources
.findOne({
_id: id,
user: req.user._id,
})
.then((ressource) => {
if (ressource) {
res.status(200).send(ressource);
} else {
res.sendStatus(404);
}
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchFile(req, res) {
let ressource = await ressources.findOne({
user: new ObjectId(req.params.userid),
_id: new ObjectId(req.params.resid),
});
if (ressource) {
res.sendFile(ressourcePath(ressource));
} else {
res.sendStatus(404);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function renameFile(req, res) {
if (req.user._id.toString() !== req.params.userid) {
res.sendStatus(403);
return;
}
if (
req.body === undefined ||
req.body.name === undefined ||
req.body.name.length <= 0 ||
/\.{2}|\/|\\/.test(req.body.name)
) {
res.sendStatus(400);
return;
}
const name = req.body.name;
let ressource = await ressources.findOne({
user: new ObjectId(req.params.userid),
filename: req.params.resid,
});
if (!ressource) {
console.log('Ressource could not be found');
res.sendStatus(400);
return;
}
ressources
.updateOne(
{
_id: ressource._id,
},
{
$set: {
name,
},
},
)
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function deleteFile(req, res) {
if (req.user._id.toString() !== req.params.userid) {
res.sendStatus(403);
return;
}
let ressource = await ressources.findOne({
user: new ObjectId(req.params.userid),
filename: req.params.resid,
});
if (!ressource) {
console.log('Ressource could not be found');
res.sendStatus(400);
return;
}
rm(ressourcePath(ressource))
.then(() => {
return ressources.deleteOne({ _id: ressource._id });
})
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchDirectory(req, res) {
if (!req.body) {
res.sendStatus(400);
return;
}
const path = req.body.path;
if (!path) {
res.sendStatus(400);
return;
}
const files = ressources.find({
path,
});
readdir(buildPath(req.user._id, path), {
withFileTypes: true,
})
.then(async (value) => {
let directories = value
.filter((dir) => dir.isDirectory())
.map((dir) => {
return {
name: dir.name,
isDir: true,
};
});
res.status(200).send([...directories, ...(await files.toArray())]);
})
.catch(async (err) => {
console.error(err);
res.status(200).send(await files.toArray());
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function addDirectory(req, res) {
if (!req.body) {
res.sendStatus(400);
return;
}
const name = req.body.name;
const path = req.body.path;
if (!name || !path || !/^[a-zA-Z0-9-_]+$/.test(name)) {
res.sendStatus(400);
return;
}
mkdir(buildPath(req.user._id, path + '/' + name))
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function deleteDirectory(req, res) {
console.log(req.body);
if (
req.body === undefined ||
req.body.path === undefined ||
req.body.path.length <= 0
) {
res.sendStatus(400);
return;
}
console.log(req.body);
const path = req.body.path;
rm(buildPath(req.user._id, path), {
force: true,
recursive: true,
})
.then(() => {
return ressources.deleteMany({
user: req.user._id,
path: {
$regex: '^' + path + '($|\\/.*)',
},
});
})
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}

22
src/db.js Normal file
View File

@@ -0,0 +1,22 @@
import { MongoClient } from 'mongodb';
/**
* @type {MongoClient}
*/
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);
}

761
src/games.js Normal file
View File

@@ -0,0 +1,761 @@
import { Collection, Db, ObjectId } from 'mongodb';
import { checkNumberProp, checkObjectProp, checkStringProp } from './util.js';
/**
* @type {Collection}
*/
let cGames;
/**
* @type {Collection}
*/
let cWalls;
/**
* @type {Collection}
*/
let cCategories;
/**
* @type {Collection}
*/
let cQuestions;
const QuestionType = {
SIMPLE: 'SIMPLE',
MULTIPLE_CHOICE: 'MULTIPLE_CHOICE',
IMAGE: 'IMAGE',
IMAGE_MULTIPLE_CHOICE: 'IMAGE_MULTIPLE_CHOICE',
AUDIO: 'AUDIO',
AUDIO_MULTIPLE_CHOICE: 'AUDIO_MULTIPLE_CHOICE',
};
/**
*
* @param {number} points
* @param {string} question
* @param {string} answer
* @param {ObjectId} owner
* @returns
*/
function createSimpleQuestion(points, question, answer, owner) {
return {
owner,
points,
type: QuestionType.SIMPLE,
data: createSimpleData(question, answer),
};
}
/**
*
* @param {string} question
* @param {string} answer
* @returns
*/
function createSimpleData(question, answer) {
return {
question,
answer,
};
}
/**
*
* @param {ObjectId[]} ids
*/
function splitQuestionIds(ids) {
let res = [];
for (let i = 0; i < ids.length; i += 5) {
res.push(ids.slice(i, i + 5));
}
return res;
}
/**
*
* @param {*} app
* @param {Db} db
*/
export function initGames(app, db) {
cGames = db.collection('games');
cWalls = db.collection('walls');
cCategories = db.collection('categories');
cQuestions = db.collection('questions');
app.get('/game', fetchGame);
app.post('/game', createGame);
app.delete('/game/:gameid', deleteGameRoute);
app.get('/games', fetchGames);
app.post('/game/rename', renameGame);
app.get('/wall', fetchWall);
app.get('/walls/:gameid', fetchWalls);
app.post('/wall', createWall);
app.delete('/wall/:wallid', deleteWallRoute);
app.post('/wall/rename', renameWall);
app.get('/category', fetchCategory);
app.post('/category/rename', renameCategory);
app.get('/question', fetchQuestion);
app.post('/question', updateQuestion);
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function createGame(req, res) {
if (!checkStringProp(req.body, 'name')) {
res.sendStatus(400);
return;
}
const name = req.body.name;
cGames
.insertOne({
name,
walls: [],
owner: req.user._id,
})
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
function renameGame(req, res) {
if (!checkStringProp(req.body, 'name')) {
res.sendStatus(400);
return;
}
if (!checkStringProp(req.body, 'gameid')) {
res.sendStatus(400);
return;
}
/**
* @type {string}
*/
let gameid = req.body.gameid;
let _id = new ObjectId(gameid);
let name = req.body.name;
cGames
.updateOne(
{
_id,
owner: req.user._id,
},
{
$set: {
name,
},
},
)
.then((result) => {
if (result.modifiedCount === 1) res.sendStatus(200);
else {
console.error(
`Failed to modify exactly one Document. Instead modified: ${result.modifiedCount}`,
);
res.sendStatus(400);
}
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchGames(req, res) {
let list = cGames.find({
owner: req.user._id,
});
res.status(200).send(await list.toArray());
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchGame(req, res) {
if (req.query.id === undefined || req.query.id.length <= 0) {
res.sendStatus(400);
return;
}
const id = new ObjectId(req.query.id);
let game = await cGames.findOne({
_id: id,
owner: req.user._id,
});
if (game) {
res.status(200).send(game);
} else {
res.sendStatus(404);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function deleteGameRoute(req, res) {
let game = await cGames.findOne({
owner: req.user._id,
_id: new ObjectId(req.params.gameid),
});
if (!game) {
res.sendStatus(404);
return;
}
deleteGame(game._id)
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchQuestion(req, res) {
if (req.query.id === undefined || req.query.id.length <= 0) {
res.sendStatus(400);
return;
}
const id = new ObjectId(req.query.id);
let question = await cQuestions.findOne({
_id: id,
owner: req.user._id,
});
if (question) {
res.status(200).send(question);
} else {
res.sendStatus(500);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchCategory(req, res) {
if (req.query.id === undefined || req.query.id.length <= 0) {
res.sendStatus(400);
return;
}
const id = new ObjectId(req.query.id);
let category = await cCategories.findOne({
_id: id,
owner: req.user._id,
});
if (category) {
let questions = await cQuestions
.find(
{
_id: {
$in: category.questions,
},
owner: req.user._id,
},
{
projection: {
_id: 1,
points: 1,
},
},
)
.toArray();
if (questions.length !== 5) {
res.sendStatus(500);
return;
}
category.questions = questions;
res.status(200).send(category);
} else {
res.sendStatus(500);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
function renameCategory(req, res) {
if (!checkStringProp(req.body, 'name')) {
res.sendStatus(400);
return;
}
if (!checkStringProp(req.body, 'categoryid')) {
res.sendStatus(400);
return;
}
/**
* @type {string}
*/
let categoryid = req.body.categoryid;
let _id = new ObjectId(categoryid);
let name = req.body.name;
cCategories
.updateOne(
{
_id,
owner: req.user._id,
},
{
$set: {
name,
},
},
)
.then((result) => {
if (result.modifiedCount === 1) res.sendStatus(200);
else {
console.error(
`Failed to modify exactly one Document. Instead modified: ${result.modifiedCount}`,
);
res.sendStatus(400);
}
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchWall(req, res) {
if (req.query.id === undefined || req.query.id.length <= 0) {
res.sendStatus(400);
return;
}
const id = new ObjectId(req.query.id);
let wall = await cWalls.findOne({
_id: id,
owner: req.user._id,
});
if (wall) {
res.status(200).send(wall);
} else {
res.sendStatus(404);
}
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function fetchWalls(req, res) {
let game = await cGames.findOne({
owner: req.user._id,
_id: new ObjectId(req.params.gameid),
});
if (!game) {
res.sendStatus(404);
return;
}
let fetchedWalls = cWalls.find({
_id: {
$in: game.walls,
},
});
res.status(200).send(await fetchedWalls.toArray());
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
function renameWall(req, res) {
if (!checkStringProp(req.body, 'name')) {
res.sendStatus(400);
return;
}
if (!checkStringProp(req.body, 'wallid')) {
res.sendStatus(400);
return;
}
/**
* @type {string}
*/
let wallid = req.body.wallid;
let _id = new ObjectId(wallid);
let name = req.body.name;
cWalls
.updateOne(
{
_id,
owner: req.user._id,
},
{
$set: {
name,
},
},
)
.then((result) => {
if (result.modifiedCount === 1) res.sendStatus(200);
else {
console.error(
`Failed to modify exactly one Document. Instead modified: ${result.modifiedCount}`,
);
res.sendStatus(400);
}
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function createWall(req, res) {
if (
!checkStringProp(req.body, 'gameid') &&
!checkStringProp(req.body, 'name')
) {
res.sendStatus(400);
return;
}
/**
* @type {string}
*/
const gameid = req.body.gameid;
/**
* @type {string}
*/
const wallname = req.body.name;
let game = await cGames.findOne({
owner: req.user._id,
_id: new ObjectId(gameid),
});
if (!game) {
res.sendStatus(404);
return;
}
let newQuestions = [];
for (let id = 1; id <= 5; id++) {
for (let j = 1; j <= 5; j++) {
newQuestions.push(
createSimpleQuestion(
j * -100,
'Frage',
'Antwort',
req.user._id,
),
);
}
}
cQuestions
.insertMany(newQuestions)
.then((insertedQuestions) => {
let questionsIds = splitQuestionIds(
Object.values(insertedQuestions.insertedIds),
);
let newCategories = [];
for (let i = 1; i <= 5; i++) {
newCategories.push({
name: `Kategorie ${i}`,
questions: questionsIds[i - 1],
owner: req.user._id,
});
}
return cCategories.insertMany(newCategories);
})
.then((insertedCategories) => {
return cWalls.insertOne({
name: wallname,
categories: Object.values(insertedCategories.insertedIds),
owner: req.user._id,
});
})
.then((insertedWall) => {
return cGames.updateOne(
{
_id: game._id,
},
{
$push: {
walls: insertedWall.insertedId,
},
},
);
})
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function deleteWallRoute(req, res) {
let wall = await cWalls.findOne({
_id: new ObjectId(req.params.wallid),
owner: req.user._id,
});
if (!wall) {
res.sendStatus(404);
return;
}
let game = await cGames.findOne({
owner: req.user._id,
walls: wall._id,
});
if (!game) {
res.sendStatus(404);
return;
}
deleteWall(wall._id)
.then(() => {
return cGames.updateOne(
{
_id: game._id,
},
{
$pull: {
walls: wall._id,
},
},
);
})
.then(() => {
res.sendStatus(200);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
/**
*
* @param {import('express').Request} req
* @param {import('express').Response} res
*/
async function updateQuestion(req, res) {
if (
!checkStringProp(req.body, '_id') &&
!checkStringProp(req.body, 'owner') &&
!checkStringProp(req.body, 'type') &&
!checkNumberProp(req.body, 'points') &&
!checkObjectProp(req.body, 'data')
) {
res.sendStatus(400);
return;
}
if (req.body.owner !== req.user._id.toString()) {
res.sendStatus(403);
return;
}
/**
* @type {string}
*/
let _id = req.body._id;
let replacement;
if (
req.body.type === QuestionType.SIMPLE ||
req.body.type === QuestionType.MULTIPLE_CHOICE
) {
replacement = toNormalQuestion(req.body);
} else if (
req.body.type === QuestionType.IMAGE ||
req.body.type === QuestionType.IMAGE_MULTIPLE_CHOICE
) {
replacement = toImageQuestion(req.body);
} else if (
req.body.type === QuestionType.AUDIO ||
req.body.type === QuestionType.AUDIO_MULTIPLE_CHOICE
) {
replacement = toAudioQuestion(req.body);
}
cQuestions
.replaceOne(
{
_id: new ObjectId(_id),
owner: req.user._id,
},
replacement,
)
.then((result) => {
if (result.modifiedCount === 1) {
res.sendStatus(200);
} else res.sendStatus(500);
})
.catch((err) => {
console.error(err);
res.sendStatus(500);
});
}
function toNormalQuestion(body) {
return {
...body,
_id: new ObjectId(body._id),
owner: new ObjectId(body.owner),
};
}
function toImageQuestion(body) {
return {
...body,
_id: new ObjectId(body._id),
owner: new ObjectId(body.owner),
data: {
...body.data,
image:
body.data.image === null ? null : new ObjectId(body.data.image),
},
};
}
function toAudioQuestion(body) {
return {
...body,
_id: new ObjectId(body._id),
owner: new ObjectId(body.owner),
data: {
...body.data,
audio:
body.data.audio === null ? null : new ObjectId(body.data.audio),
},
};
}
/**
*
* @param {ObjectId} _id
*/
function deleteGame(_id) {
return cGames
.findOne({ _id })
.then((game) => {
let wallDeletions = [];
for (const wallId of game.walls) {
wallDeletions.push(deleteWall(wallId));
}
return Promise.all(wallDeletions);
})
.then(() => {
return cGames.deleteOne({ _id });
});
}
/**
*
* @param {ObjectId} _id
*/
function deleteWall(_id) {
return cWalls
.findOne({ _id })
.then((wall) => {
let categoryDeletions = [];
for (const catId of wall.categories) {
categoryDeletions.push(deleteCategory(catId));
}
return Promise.all(categoryDeletions);
})
.then(() => {
return cWalls.deleteOne({ _id: _id });
});
}
/**
*
* @param {ObjectId} _id
*/
function deleteCategory(_id) {
return cCategories
.findOne({
_id,
})
.then((category) => {
return cQuestions.deleteMany({
_id: {
$in: category.questions,
},
});
})
.then(() => {
return cCategories.deleteOne({
_id,
});
});
}

12
src/roles.js Normal file
View File

@@ -0,0 +1,12 @@
export const roles = [
"admin",
"default"
]
/**
*
* @param {string} newrole
*/
export function isValidRole(newrole) {
return roles.includes(newrole);
}

156
src/user.js Normal file
View File

@@ -0,0 +1,156 @@
import { Db, ObjectId } from "mongodb";
import { createUser as userHelperCreateUser, generateSessionToken, updatePassword, userExists } from "./userHelper.js";
import { isValidRole, roles } from "./roles.js";
import { authenticateUser } from "./auth.js";
let db;
let users;
/**
*
* @param {*} app
* @param {Db} db
*/
export function initUsers(app, db) {
users = db.collection('users');
app.put('/admin/user', createUser);
app.delete('/admin/user', deleteUser);
app.get('/admin/user/list', userlist);
app.post('/admin/user/resetpw', resetpassword);
app.post('/admin/user/changerole', changerole);
app.get('/admin/roles', getRoles);
app.post('/user/changepw', changePassword);
app.post('/user/logout', logoutUser);
}
async function createUser(req, res) {
const username = req.body.username;
if (username.length <= 0) {
res.status(400).send();
return;
}
// check if user exists
let foundUser = await users.findOne({username});
if (foundUser !== null) {
res.status(400).send();
return;
}
const password = generateSessionToken(10);
const userobj = await userHelperCreateUser(users, username, password, 'default', false);
res.status(200).send({
username: userobj.username,
role: userobj.role,
_id: userobj._id,
password
});
}
async function deleteUser(req, res) {
/** @type {string} */
const userid = req.body.userid;
const _id = new ObjectId(userid);
if (userid === req.user._id.toString()) {
console.log("Cant delete yourself");
res.status(400).send();
return;
}
const foundUser = userExists(res, users, _id);
if (foundUser === null) return;
await users.deleteOne({_id});
res.status(200).send();
}
async function userlist(req, res) {
const result = await users.find().project({
username: 1,
role: 1
}).toArray();
res.status(200).send(result);
}
async function resetpassword(req, res) {
/** @type {string} */
const userid = req.body.userid;
const _id = new ObjectId(userid);
const foundUser = userExists(res, users, _id);
if (foundUser === null) return;
const password = generateSessionToken(10);
await updatePassword(users, _id, password, false);
res.status(200).send({
_id: userid,
username: foundUser.username,
role: foundUser.role,
password
});
}
async function changerole(req, res) {
/** @type {string} */
const userid = req.body.userid;
const _id = new ObjectId(userid);
const newrole = req.body.role;
if (!isValidRole(newrole)) {
res.status(400).send("No valid role");
return;
}
const foundUser = await userExists(res, users, _id);
if (foundUser === null) return;
await users.updateOne({_id}, {
$set: {
role: newrole
}
});
res.status(200).send({
_id,
username: foundUser.username,
role: newrole
});
}
function getRoles(req, res) {
res.status(200).send(roles);
}
async function changePassword(req, res) {
const oldpassword = req.body.old;
const newpassword = req.body.new;
const userobj = await authenticateUser(req.user.username, oldpassword, false);
if (userobj === null) {
res.status(400).send();
return;
}
await updatePassword(users, req.user._id, newpassword, false);
res.status(200).send();
}
async function logoutUser(req, res) {
await users.updateOne({_id: req.user._id}, {
$set: {
sessiontoken: ""
}
});
res.status(200).send();
}

76
src/userHelper.js Normal file
View File

@@ -0,0 +1,76 @@
import { pbkdf2Sync, randomBytes } from "node:crypto";
export async function createUser(collection, username, password, role, withSession = true) {
const {salt, iterations, hash} = createHash(password);
let sessiontoken = "";
if (withSession) {
sessiontoken = generateSessionToken();
}
const result = await collection.insertOne({
username,
role,
salt,
iterations,
hash,
sessiontoken
});
return {sessiontoken, username, role, _id: result.insertedId};
}
export async function updatePassword(collection, _id, password, keepSession = true) {
const {salt, iterations, hash} = createHash(password);
if (keepSession) {
await collection.updateOne({_id}, {$set: {
salt,
iterations,
hash
}});
} else {
await collection.updateOne({_id}, {$set: {
salt,
iterations,
hash,
sessiontoken: ""
}});
}
}
export function generateSessionToken(length = 128, encoding = 'base64') {
return randomBytes(length).toString(encoding);
}
export function generateHash(password, salt, iterations) {
return pbkdf2Sync(password, salt, iterations, 128, 'sha512').toString('hex');
}
export async function updateSessionToken(collection, _id) {
const sessiontoken = generateSessionToken();
await collection.updateOne({_id: _id}, {$set: {
sessiontoken
}});
return sessiontoken;
}
export async function userExists(res, collection, _id) {
const foundUser = await collection.findOne({_id});
if (foundUser === null) {
res.status(400).send();
}
return foundUser;
}
function createHash(password) {
const salt = randomBytes(128).toString('base64');
const iterations = Math.floor(Math.random() * 5000) + 5000;
const hash = generateHash(password, salt, iterations);
return {
salt, hash, iterations
}
}

37
src/util.js Normal file
View File

@@ -0,0 +1,37 @@
/**
*
* @param {any} body
* @param {string} property
*/
export function checkStringProp(body, property) {
if (body === undefined) return false;
if (Object.hasOwn(body, property)) {
if (typeof body[property] === 'string') {
return body[property].length > 0;
} else return false;
} else return false;
}
/**
*
* @param {any} body
* @param {string} property
*/
export function checkNumberProp(body, property) {
if (body === undefined) return false;
if (Object.hasOwn(body, property)) {
return typeof body[property] === 'number';
} else return false;
}
/**
*
* @param {any} body
* @param {string} property
*/
export function checkObjectProp(body, property) {
if (body === undefined) return false;
if (Object.hasOwn(body, property)) {
return typeof body[property] === 'object';
} else return false;
}

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