Compare commits
7 Commits
1.0.1
...
a197d9bd3b
| Author | SHA1 | Date | |
|---|---|---|---|
| a197d9bd3b | |||
| 91cdc9e08a | |||
| e4c038c940 | |||
| 2bae9db84f | |||
| f99aee302a | |||
| f1d5bead86 | |||
| 216f977165 |
13
.vscode/settings.json
vendored
Normal file
13
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"rest-client.environmentVariables": {
|
||||
"$shared": {},
|
||||
"local": {
|
||||
"host": "localhost",
|
||||
"port": "12345"
|
||||
},
|
||||
"docker": {
|
||||
"host": "localhost",
|
||||
"port": "11001"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ FROM node:${NODE_VERSION}-alpine
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/node_modules node_modules/
|
||||
COPY --from=builder /app/index.js .
|
||||
COPY --from=builder /app/src src/
|
||||
USER node
|
||||
EXPOSE 12345
|
||||
ENV NODE_ENV=production
|
||||
|
||||
32
Readme.md
Normal file
32
Readme.md
Normal 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
|
||||
```
|
||||
134
index.js
134
index.js
@@ -1,111 +1,35 @@
|
||||
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 { close as closeDbConnection, initDbConnection, db } from "./src/db.js";
|
||||
import { initUsers } from "./src/user.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(cors({credentials: true, origin: process.env.JEOPARDY_URL}));
|
||||
app.use(morgan(process.env.production ? 'common' : 'dev'));
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
|
||||
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);
|
||||
initUsers(app);
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
1249
package-lock.json
generated
1249
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
13
package.json
13
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "jeopardyserver",
|
||||
"version": "1.0.1",
|
||||
"version": "1.0.2",
|
||||
"description": "",
|
||||
"license": "ISC",
|
||||
"author": "",
|
||||
@@ -11,6 +11,17 @@
|
||||
"docker-build": "docker build -t jeopardyserver ."
|
||||
},
|
||||
"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",
|
||||
"ws": "^8.18.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.6.0"
|
||||
}
|
||||
}
|
||||
|
||||
10
requests/test.http
Normal file
10
requests/test.http
Normal 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
106
src/auth.js
Normal 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,
|
||||
path: "/"
|
||||
})
|
||||
|
||||
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
21
src/db.js
Normal 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();
|
||||
}
|
||||
9
src/user.js
Normal file
9
src/user.js
Normal file
@@ -0,0 +1,9 @@
|
||||
|
||||
|
||||
export function initUsers(app) {
|
||||
app.get('/user/username', returnUsername);
|
||||
}
|
||||
|
||||
function returnUsername(req, res) {
|
||||
res.status(200).send(req.user.username);
|
||||
}
|
||||
103
src/websocket.js
Normal file
103
src/websocket.js
Normal 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();
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user