Skip to content

Commit

Permalink
Merge pull request #6 from Avelous/staging
Browse files Browse the repository at this point in the history
Updates to Dice Demonstration
  • Loading branch information
ZakGriffith authored Feb 13, 2024
2 parents c45e637 + 33221d1 commit 0124e57
Show file tree
Hide file tree
Showing 26 changed files with 694 additions and 523 deletions.
64 changes: 35 additions & 29 deletions packages/backend/controllers/Admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import { Request, Response } from "express";
import jwt from "jsonwebtoken";
import { ably } from "..";

const JWT_SECRET = process.env.JWT_SECRET || "superhardstring";

async function generateUniqueInvite(length: number) {
const JWT_SECRET = process.env.JWT_SECRET || "superhardstring";
let invites = await Invites.findOne();

if (!invites) {
Expand Down Expand Up @@ -40,7 +41,7 @@ async function generateUniqueInvite(length: number) {

export const createGame = async (req: Request, res: Response) => {
try {
const { maxPlayers, diceCount, hiddenChars, privateKey, prize, mode, adminAddress } = req.body;
const { diceCount, hiddenChars, privateKey, hiddenPrivateKey, mode, adminAddress } = req.body;

const salt = await bcrypt.genSalt();
// const privateKeyHash = await bcrypt.hash(privateKey, salt);
Expand All @@ -49,12 +50,11 @@ export const createGame = async (req: Request, res: Response) => {
adminAddress,
status: "ongoing",
inviteCode: await generateUniqueInvite(8),
maxPlayers,
diceCount,
mode,
privateKey,
hiddenPrivateKey,
hiddenChars,
prize,
});

let token;
Expand All @@ -68,6 +68,36 @@ export const createGame = async (req: Request, res: Response) => {
}
};

export const restartWithNewPk = async (req: Request, res: Response) => {
try {
const { diceCount, hiddenChars, privateKey, hiddenPrivateKey, adminAddress } = req.body;
const { id } = req.params;
const game = await Game.findById(id);

if (game?.status !== "finished") {
return res.status(400).json({ error: "Game is not finished." });
}

game.diceCount = diceCount;
game.hiddenChars = hiddenChars;
game.privateKey = privateKey;
game.hiddenPrivateKey = hiddenPrivateKey;
game.mode = "manual";
game.adminAddress = adminAddress;
game.winner = undefined;
game.status = "ongoing";

const updatedGame = await game.save();
console.log(updatedGame);

const channel = ably.channels.get(`gameUpdate`);
channel.publish(`gameUpdate`, updatedGame);
res.status(200).json(updatedGame);
} catch (err) {
res.status(500).json({ error: (err as Error).message });
}
};

export const pauseGame = async (req: Request, res: Response) => {
try {
const { id } = req.params;
Expand Down Expand Up @@ -167,7 +197,7 @@ export const changeGameMode = async (req: Request, res: Response) => {
// return res.status(400).json({ error: "Game is not paused." });
// }

if (mode !== "auto" && mode !== "manual") {
if (mode !== "auto" && mode !== "manual" && mode !== "brute") {
return res.status(400).json({ error: "Invalid game mode." });
}

Expand All @@ -184,30 +214,6 @@ export const changeGameMode = async (req: Request, res: Response) => {
}
};

export const changePrize = async (req: Request, res: Response) => {
try {
const { gameId } = req.params;
const { newPrize } = req.body;

const game = await Game.findById(gameId);

if (!game) {
return res.status(404).json({ error: "Game not found." });
}

if (game.status !== "ongoing") {
return res.status(400).json({ error: "Game is not ongoing." });
}

game.prize = newPrize;
const updatedGame = await game.save();

res.status(200).json(updatedGame);
} catch (err) {
res.status(500).json({ error: (err as Error).message });
}
};

export const kickPlayer = async (req: Request, res: Response) => {
try {
const { id } = req.params;
Expand Down
6 changes: 1 addition & 5 deletions packages/backend/controllers/Player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ export const join = async (req: Request, res: Response) => {
return res.status(400).json({ error: "Game is not ongoing." });
}

if (game.players.length >= game.maxPlayers) {
return res.status(400).json({ error: "Game is full." });
}

if (game.players.includes(playerAddress)) {
return res.status(200).json(game); // Player is already in the game
}
Expand All @@ -32,7 +28,7 @@ export const join = async (req: Request, res: Response) => {

game.players.push(playerAddress);
const savedGame = await game.save();

const channel = ably.channels.get(`gameUpdate`);
channel.publish(`gameUpdate`, savedGame);
res.status(200).json({ token, game: savedGame });
Expand Down
6 changes: 5 additions & 1 deletion packages/backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use(morgan("common"));
app.use(bodyParser.json({ limit: "30mb" }));
app.use(bodyParser.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());
app.use(
cors({
origin: "*",
}),
);

/**Ably Setup */

Expand Down
19 changes: 6 additions & 13 deletions packages/backend/models/Game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ const gameSchema = new mongoose.Schema(
type: String,
required: true,
},
maxPlayers: {
type: Number,
required: true,
min: 5,
max: 30,
},
diceCount: {
type: Number,
required: true,
Expand All @@ -29,27 +23,26 @@ const gameSchema = new mongoose.Schema(
},
mode: {
type: String,
enum: ["auto", "manual"],
enum: ["auto", "manual", "brute"],
required: true,
},
privateKey: {
type: String,
required: true,
},
hiddenPrivateKey: {
type: String,
required: false,
},
hiddenChars: {
type: Object,
required: true,
},
prize: {
type: Number,
required: true,
},
players: {
type: [String],
default: [],
validate: {
validator: function (value: [string]) {
// Check if the array only contains unique strings
const uniqueStrings: string[] = [];
value.forEach(item => {
if (!uniqueStrings.includes(item)) {
Expand All @@ -58,7 +51,7 @@ const gameSchema = new mongoose.Schema(
});
return uniqueStrings.length === value.length;
},
message: "The players array must contain unique strings.",
message: "The players array must contain unique addresses.",
},
},
winner: {
Expand Down
4 changes: 0 additions & 4 deletions packages/backend/models/Player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,6 @@ const playerSchema = new mongoose.Schema(
key: String,
value: String,
},
prize: {
type: Number,
required: true,
},
},
{ timestamps: true },
);
Expand Down
3 changes: 2 additions & 1 deletion packages/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"name": "@se-2/backend",
"version": "0.0.1",
"scripts": {
"backend": "ts-node index.ts"
"backend": "ts-node index.ts",
"start": "ts-node index.ts"
},
"dependencies": {
"ably": "^1.2.45",
Expand Down
3 changes: 2 additions & 1 deletion packages/backend/routes/admin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express from "express";
import { createGame, changeGameMode, pauseGame, resumeGame, kickPlayer } from "../controllers/Admin";
import { createGame, changeGameMode, pauseGame, resumeGame, kickPlayer, restartWithNewPk } from "../controllers/Admin";
import { verifyToken } from "../middleware/auth";

const router = express.Router();
Expand All @@ -9,5 +9,6 @@ router.patch("/changemode/:id", verifyToken, changeGameMode);
router.patch("/pause/:id", verifyToken, pauseGame);
router.patch("/resume/:id", verifyToken, resumeGame);
router.patch("/kickplayer/:id", verifyToken, kickPlayer);
router.patch("/restartwithnewpk/:id", verifyToken, restartWithNewPk);

export default router;
11 changes: 11 additions & 0 deletions packages/backend/vercel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": 2,
"name": "dice-demonstration-backend",
"builds": [
{ "src": "index.ts", "use": "@vercel/node" }
],
"routes": [
{ "src": "/(.*)", "dest": "/index.ts" }
]
}

Loading

0 comments on commit 0124e57

Please sign in to comment.