Files
dndmaster/backend/server.js
T
Marces Zastrow 5a46333bfd +
Added functionallity to start a new Game
2024-12-19 11:08:22 +01:00

140 lines
4.6 KiB
JavaScript

const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt');
const cors = require('cors');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const app = express();
const port = 5000;
// Middleware
app.use(cors());
app.use(bodyParser.json());
// SQLite database setup
const db = new sqlite3.Database('./database.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to SQLite database.');
}
});
// Create users table if it doesn't exist
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
email TEXT UNIQUE,
password TEXT
)`);
// Create games table if it doesn't exist
db.run(`CREATE TABLE IF NOT EXISTS games (
game_id TEXT PRIMARY KEY,
name TEXT,
description TEXT,
game_master_id INTEGER,
participants TEXT
)`);
// Registration route
app.post('/register', async (req, res) => {
const { username, email, password } = req.body;
console.log("Trying to Register: ", username);
try {
const hashedPassword = await bcrypt.hash(password, 10);
const stmt = db.prepare('INSERT INTO users (username, email, password) VALUES (?, ?, ?)');
stmt.run([username, email, hashedPassword], function (err) {
if (err) {
return res.status(400).json({ error: 'User already exists or invalid data.' });
}
res.status(201).json({ message: 'User registered successfully!', userId: this.lastID });
});
stmt.finalize();
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
// Login route
app.post('/login', (req, res) => {
const { username, password } = req.body;
console.log("Trying to Login: ", username);
db.get('SELECT * FROM users WHERE username = ?', [username], async (err, row) => {
if (err) {
return res.status(500).json({ error: 'Internal server error' });
}
if (!row || !(await bcrypt.compare(password, row.password))) {
return res.status(400).json({ error: 'Invalid username or password.' });
}
res.json({ message: 'Login successful!', userId: row.id });
});
});
// Fetch games for a specific user
app.get('/games/:userId', (req, res) => {
const userId = req.params.userId;
db.all(
`SELECT * FROM games WHERE game_master_id = ? OR participants LIKE ?`,
[userId, `%${userId}%`],
(err, rows) => {
if (err) {
return res.status(500).json({ error: 'Internal server error' });
}
res.json(rows);
}
);
});
//Join Game
app.post('/joinGame/:gameId', (req, res) => {
const gameId = req.params.gameId;
const userId = req.body.userId;
const stmt = db.prepare('INSERT INTO games (participants) VALUES (?) WHERE game_id IS (?)');
stmt.run([gameId, userId], function(err) {
if (err) {
return res.status(400).json({ error: 'Failed to create game.' });
}
res.status(201).json({message: "User joined Game!", gameId: this.gameId})
})
stmt.finalize();
});
// Create a new game
app.post('/games', (req, res) => {
const { name, description, gameMasterId, participants } = req.body;
const stmt = db.prepare('INSERT INTO games (name, description, game_master_id, participants) VALUES (?, ?, ?, ?)');
stmt.run([name, description, gameMasterId, JSON.stringify(participants)], function (err) {
if (err) {
return res.status(400).json({ error: 'Failed to create game.' });
}
res.status(201).json({ message: 'Game created successfully!', gameId: this.lastID });
});
stmt.finalize();
});
app.post('/createGame', (req, res) => {
const { name, description, gameMasterId, participants } = req.body;
// Generate an 8-character alphanumeric ID
const gameId = crypto.randomBytes(4).toString('hex'); // 8 characters (4 bytes * 2 hex chars per byte)
const stmt = db.prepare('INSERT INTO games (game_id, name, description, game_master_id, participants) VALUES (?, ?, ?, ?, ?)');
stmt.run([gameId, name, description, gameMasterId, JSON.stringify(participants)], function (err) {
if (err) {
return res.status(400).json({ error: 'Failed to create game.' });
}
res.status(201).json({ message: 'Game created successfully!', gameId: gameId });
});
stmt.finalize();
});
// Start the server
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});