Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web: Config file #102

Merged
merged 15 commits into from
Mar 15, 2024
Merged
6 changes: 3 additions & 3 deletions comprl-web/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ npm start

Now you'll need to pick a host to deploy it to.

## Key
The current key is `1234`.
You can change the key in the file `comprl-web/app/routes/_dashboard.register.tsx`.
## Config File
The `user_db_path`, the `user_db_name` and the `key` are defined in the config file `config.toml`.
The current key is `1234`.
31 changes: 31 additions & 0 deletions comprl-web/app/config.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { readFileSync } from 'fs';
import { parse } from 'toml';

export function parseArgs() {
const args: { [key: string]: string } = {}; // Add index signature
process.argv
.slice(2, process.argv.length)
.forEach(arg => {
const longArg = arg.split('=');
args[longArg[0]] = longArg[1];
});
return args;
}

export function parseConfig() {
const args = parseArgs();
console.log(args);
const configFilePath = args['config'] || 'config.toml';
try {
console.log('Reading configuration file:', configFilePath);
const tomlData = readFileSync(configFilePath, 'utf8');
const parsedData = parse(tomlData);
const str = JSON.stringify(parsedData)
return JSON.parse(str);
} catch (error) {
console.error('Error reading the configuration file:', error);
return null;
}
}

export const config = parseConfig();
47 changes: 27 additions & 20 deletions comprl-web/app/db/sqlite.data.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import Database from 'better-sqlite3';
import { User, Statistics, Game } from './types';
import { v4 as uuidv4 } from 'uuid';
import { config } from "~/config";

console.log('Creating users.db');
const userDB = new Database('users.db', { verbose: console.log });
console.log(config);
const user_db_path = config.Web.user_db_path;
const user_db_name = config.Web.user_db_name;
const game_db_path = config.Web.game_db_path;
const game_db_name = config.Web.game_db_name;

console.log(`Creating ${user_db_path}`);
const userDB = new Database(user_db_path, { verbose: console.log });
userDB.prepare(`
CREATE TABLE IF NOT EXISTS users(
CREATE TABLE IF NOT EXISTS ${user_db_name}(
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL,
Expand All @@ -16,10 +23,10 @@ userDB.prepare(`
`).run();
userDB.close();

console.log('Creating game.db');
const gameDB = new Database('game.db', { verbose: console.log });
console.log(`Creating ${game_db_path}`);
const gameDB = new Database(game_db_path, { verbose: console.log });
gameDB.prepare(`
CREATE TABLE IF NOT EXISTS data (
CREATE TABLE IF NOT EXISTS ${game_db_name} (
game_id TEXT NOT NULL PRIMARY KEY,
user1 INTEGER NOT NULL,
user2 INTEGER NOT NULL,
Expand All @@ -33,16 +40,16 @@ gameDB.prepare(`
gameDB.close();

export async function addUser(username: string, password: string, role: string = 'user') {
const userDB = new Database('users.db', { verbose: console.log });
const userDB = new Database(user_db_path, { verbose: console.log });
const token = uuidv4();
const stmt = userDB.prepare('INSERT INTO users(username, password, role, token) VALUES (?, ?, ?,?)');
const stmt = userDB.prepare(`INSERT INTO ${user_db_name}(username, password, role, token) VALUES (?, ?, ?, ?)`);
stmt.run(username, password, role, token);
userDB.close();
}

export async function getUser(username: string, password: string) {
const userDB = new Database('users.db', { verbose: console.log });
const stmt = userDB.prepare('SELECT * FROM users WHERE username = ?');
const userDB = new Database(user_db_path, { verbose: console.log });
const stmt = userDB.prepare(`SELECT * FROM ${user_db_name} WHERE username = ?`);
const res = stmt.get(username);
userDB.close();
if (!res) { return undefined }
Expand All @@ -51,17 +58,17 @@ export async function getUser(username: string, password: string) {
}

export async function getUsername(user_id: number) {
const userDB = new Database('users.db', { verbose: console.log });
const stmt = userDB.prepare('SELECT username FROM users WHERE user_id = ?');
const userDB = new Database(user_db_path, { verbose: console.log });
const stmt = userDB.prepare(`SELECT username FROM ${user_db_name} WHERE user_id = ?`);
const res = stmt.get(user_id);
userDB.close();
return res.username;
}


export async function getAllUsers() {
const db = new Database('users.db', { verbose: console.log });
const query = 'SELECT * FROM users';
const db = new Database(user_db_path, { verbose: console.log });
const query = `SELECT * FROM ${user_db_name}`;
const users = db.prepare(query).all();
db.close();
return users;
Expand All @@ -82,15 +89,15 @@ export async function getRankedUsers() {


export async function getStatistics(user_id: number) {
const gameDB = new Database('game.db', { verbose: console.log });
const gameDB = new Database(game_db_path, { verbose: console.log });

const stmt_played = gameDB.prepare('SELECT COUNT(*) FROM data WHERE user1 = ? OR user2 = ?');
const stmt_played = gameDB.prepare(`SELECT COUNT(*) FROM ${game_db_name} WHERE user1 = ? OR user2 = ?`);
const playedGames = stmt_played.get(user_id, user_id)['COUNT(*)'];

const stmt_won = gameDB.prepare('SELECT COUNT(winner) FROM data WHERE winner = ?');
const stmt_won = gameDB.prepare(`SELECT COUNT(winner) FROM ${game_db_name} WHERE winner = ?`);
const wonGames = stmt_won.get(user_id)['COUNT(winner)'];

const stmt_disconnect = gameDB.prepare('SELECT COUNT(disconnected) FROM data WHERE disconnected = ?');
const stmt_disconnect = gameDB.prepare(`SELECT COUNT(disconnected) FROM ${game_db_name} WHERE disconnected = ?`);
const disconnectedGames = stmt_disconnect.get(user_id)['COUNT(disconnected)'];

gameDB.close();
Expand Down Expand Up @@ -125,8 +132,8 @@ export async function composeGame(game: Game) {
}

export async function getGame(game_id: string) {
const gameDB = new Database('game.db', { verbose: console.log });
const stmt = gameDB.prepare('SELECT * FROM data WHERE game_id=?');
const gameDB = new Database(game_db_path, { verbose: console.log });
const stmt = gameDB.prepare(`SELECT * FROM ${game_db_name} WHERE game_id=?`);
const game = stmt.get(game_id)
gameDB.close();

Expand Down
4 changes: 2 additions & 2 deletions comprl-web/app/routes/_auth.register.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import { ActionFunctionArgs, redirect } from "@remix-run/node";
import { Form, useActionData } from "@remix-run/react";
import { useState } from "react";
import { addUser } from "~/db/sqlite.data";

import { config } from "~/config";

export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData()
const key = formData.get("key") as string;
const username = formData.get("username") as string;
const password = formData.get("password") as string;

if (key !== "1234") {
if (key !== config.Web.key) {
return {
alerts: [{ severity: "error", message: "Invalid key" }]
}
Expand Down
6 changes: 6 additions & 0 deletions comprl-web/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[Web]
user_db_path = "user.db"
user_db_name = "data"
game_db_path = "game.db"
game_db_name = "data"
key = "1234"
10 changes: 8 additions & 2 deletions comprl-web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions comprl-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"dependencies": {
"@emotion/react": "^11.11.3",
"@emotion/styled": "^11.11.0",
"@iarna/toml": "^2.2.5",
"@mui/icons-material": "^5.15.12",
"@mui/material": "^5.15.10",
"@remix-run/css-bundle": "^2.6.0",
Expand All @@ -26,6 +27,7 @@
"react-dom": "^18.2.0",
"remix-auth": "^3.6.0",
"remix-auth-form": "^1.4.0",
"toml": "^3.0.0",
"uuid": "^9.0.1"
},
"devDependencies": {
Expand Down
5 changes: 5 additions & 0 deletions comprl-web/remix.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@ export default {
// assetsBuildDirectory: "public/build",
// publicPath: "/build/",
// serverBuildPath: "build/index.js",
browserNodeBuiltinsPolyfill: {
modules: {
fs: true
}
}
};
Loading