From 8d34bfe64f724624a1b4c7825412526d630d7b07 Mon Sep 17 00:00:00 2001 From: Aelita4 Date: Mon, 4 Nov 2024 10:26:05 +0100 Subject: [PATCH] Fix register script --- src/lib/db/planets.ts | 5 + src/lib/db/sectors.ts | 4 + src/lib/db/systems.ts | 5 + src/lib/db/users.ts | 11 +- src/pages/api/auth/generateAccessToken.ts | 18 ++-- src/pages/game/index.astro | 4 +- src/pages/login.astro | 2 +- src/pages/register.astro | 117 +++++++++++----------- 8 files changed, 92 insertions(+), 74 deletions(-) diff --git a/src/lib/db/planets.ts b/src/lib/db/planets.ts index 390e625..990b4a7 100644 --- a/src/lib/db/planets.ts +++ b/src/lib/db/planets.ts @@ -10,6 +10,11 @@ export const getPlanetById = async (id: ObjectId) => { return await (await Planets()).findOne({ _id: id }) as DBPlanet; } +export const createPlanet = async (planet: DBPlanet) => { + const planets = await Planets(); + return await planets.insertOne(planet); +} + export const updatePlanetResources = async (planetId: ObjectId, resources: Array) => { const planets = await Planets(); await planets.updateOne({ _id: planetId }, { diff --git a/src/lib/db/sectors.ts b/src/lib/db/sectors.ts index 4b65e53..2d4f8fd 100644 --- a/src/lib/db/sectors.ts +++ b/src/lib/db/sectors.ts @@ -10,4 +10,8 @@ export const getSectorById = async (id: ObjectId) => { return await (await Sectors()).findOne({ _id: id }) as DBSector; +} + +export const addSystemToSector = async (sectorId: ObjectId, systemId: ObjectId) => { + return await (await Sectors()).updateOne({ _id: sectorId }, { $push: { systems: systemId } }); } \ No newline at end of file diff --git a/src/lib/db/systems.ts b/src/lib/db/systems.ts index 9b55015..5842fbe 100644 --- a/src/lib/db/systems.ts +++ b/src/lib/db/systems.ts @@ -12,6 +12,11 @@ export const getSystemById = async (id: ObjectId) => { }) as DBSystem; } +export const createSystem = async (system: DBSystem) => { + const systems = await Systems(); + return await systems.insertOne(system); +} + export const updateSystemStructures = async (systemId: ObjectId, structures: Array<{ id: string, level: number }>) => { const systems = await Systems(); await systems.updateOne({ _id: systemId }, { diff --git a/src/lib/db/users.ts b/src/lib/db/users.ts index 5f9d586..fa390ed 100644 --- a/src/lib/db/users.ts +++ b/src/lib/db/users.ts @@ -10,8 +10,9 @@ export const getAllUsers = async () => { return users.find({}).toArray() as Promise; } -export const createUser = async (username: string, email: string, password: string) => { - const user = { +export const createUser = async (id: ObjectId, username: string, email: string, password: string, mainPlanet: ObjectId) => { + const user: DBUser = { + _id: id, username, email, password: await hash(password), @@ -19,13 +20,11 @@ export const createUser = async (username: string, email: string, password: stri createdAt: new Date(), updatedAt: new Date(), research: [], + mainPlanet } - await (await Users()).insertOne(user); - const newUser = await getUserByNickOrEmail(username); - if(!newUser) return user; - return newUser; + return user; } export const deleteUser = async (id: ObjectId) => { diff --git a/src/pages/api/auth/generateAccessToken.ts b/src/pages/api/auth/generateAccessToken.ts index 123fb2e..9dc30d8 100644 --- a/src/pages/api/auth/generateAccessToken.ts +++ b/src/pages/api/auth/generateAccessToken.ts @@ -60,18 +60,18 @@ export const POST: APIRoute = async({ request }) => { const tokenString = `A.${timestamp}.${userEncoded}.${random}`; - const user = locationManager.getUser(userFromDb._id); - if(!user) return new Response( - JSON.stringify({ - code: 404, - message: "Not found", - error: `User ${data.username} not found` - }), { status: 404 } - ) + // const user = locationManager.getUser(userFromDb._id); + // if(!user) return new Response( + // JSON.stringify({ + // code: 404, + // message: "Not found", + // error: `User ${data.username} not found` + // }), { status: 404 } + // ) const accessToken: AccessToken = { type: "A", - user, + user: userFromDb, entropy: randomHashed.toString(), createdAt: now, expiresAt: new Date(now.getTime() + expiresIn), diff --git a/src/pages/game/index.astro b/src/pages/game/index.astro index 69265ea..edb7bcf 100644 --- a/src/pages/game/index.astro +++ b/src/pages/game/index.astro @@ -13,12 +13,12 @@ if(loggedToken === null || username === "") return Astro.redirect('/logout'); const checkUser = await getUserByAccessToken(loggedToken); if(checkUser === null || checkUser.username !== username) return Astro.redirect('/logout'); -if(currentPlanetId === null) return Astro.redirect('/game/logout'); const currentPlanetId = Astro.cookies.get('currentPlanet')?.value ?? null; +if(currentPlanetId === null) return Astro.redirect('/logout'); const currentPlanet = locationManager.getPlanet(new ObjectId(currentPlanetId)); if(currentPlanet === undefined) { Astro.cookies.delete('planetid'); - return Astro.redirect('/game/logout'); + return Astro.redirect('/logout'); } --- diff --git a/src/pages/login.astro b/src/pages/login.astro index e5c38bd..10a83d0 100644 --- a/src/pages/login.astro +++ b/src/pages/login.astro @@ -27,7 +27,7 @@ if(Astro.request.method === "POST") { if(!user) throw new Error("User not found"); const sessionTime = config.SESSION_TIME_MINUTES * 60; - const res = await fetch(`https://localhost:4321/api/auth/generateAccessToken`, { + const res = await fetch(`${Astro.url.origin}/api/auth/generateAccessToken`, { method: 'POST', body: JSON.stringify({ username, diff --git a/src/pages/register.astro b/src/pages/register.astro index 15f3a0b..93802ba 100644 --- a/src/pages/register.astro +++ b/src/pages/register.astro @@ -1,10 +1,19 @@ --- -import Layout from '../layouts/Layout.astro'; import NavBar from '../components/NavBar.astro'; +import Layout from '../layouts/Layout.astro'; import { createUser } from '../lib/db/users'; +import { AstroCookieSetOptions } from 'astro'; +import { ObjectId } from 'mongodb'; import config from '../../config.json'; +import { getAllGalaxies } from '../lib/db/galaxies'; +import { createPlanet } from '../lib/db/planets'; +import { addSystemToSector } from '../lib/db/sectors'; +import { createSystem } from '../lib/db/systems'; +import DBPlanet from '../types/db/DBPlanet'; +import DBSystem from '../types/db/DBSystem'; +import locationManager from '../lib/classes/managers/LocationManager'; let error = ""; @@ -15,52 +24,24 @@ if(Astro.request.method === "POST") { const password = data.get("password") as string | ""; const password2 = data.get("password2") as string | ""; - if(username === "") { - error = "username is required"; - Astro.redirect("/register"); - } - - if(email === "") { - error = "email is required"; - Astro.redirect("/register"); - } - - if(password === "") { - error = "password is required"; - Astro.redirect("/register"); - } - - if(password2 === "") { - error = "password2 is required"; - Astro.redirect("/register"); - } - - if(username.length < 3 || username.length > 20) { - error = "username must be between 3 and 20 characters long"; - Astro.redirect("/register"); - } - - if(email.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) === null) { - error = "email is invalid"; - Astro.redirect("/register"); - } - - if(password.length < 8 || password.length > 50) { - error = "password must be between 8 and 50 characters long"; - Astro.redirect("/register"); - } - - if(password !== password2) { - error = "passwords must match"; - Astro.redirect("/register"); - } + if(username === "") error = "username is required"; + if(username.match(/^[a-zA-Z0-9]{3,20}$/) === null) error = "username must be between 3 and 20 characters long and can only contain letters and numbers"; + if(email === "") error = "email is required"; + if(email.match(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/) === null) error = "email is invalid"; + if(password === "") error = "password is required"; + if(password2 === "") error = "password2 is required"; + if(password.length < 8 || password.length > 50) error = "password must be between 8 and 50 characters long"; + if(password !== password2) error = "passwords must match"; if(error === "") { - const user = await createUser(username, email, password); + const userId = new ObjectId(); + const planetId = new ObjectId(); + + const user = await createUser(userId, username, email, password, planetId); const sessionTime = config.SESSION_TIME_MINUTES * 60; - const res = await fetch(`https://localhost:4321/api/auth/generateAccessToken`, { + const res = await fetch(`${Astro.url.origin}/api/auth/generateAccessToken`, { method: 'POST', body: JSON.stringify({ username, @@ -75,26 +56,50 @@ if(Astro.request.method === "POST") { const token = (await res.json()).accessToken; - Astro.cookies.set("sessionToken", token, { - path: "/", - maxAge: sessionTime, - sameSite: "lax", - secure: true - }); + const galaxyIndex = Math.floor(Math.random() * 4); + const sectorIndex = Math.floor(Math.random() * 8); - Astro.cookies.set("username", username, { - path: "/", - maxAge: sessionTime, - sameSite: "lax", - secure: true - }); + const planetData: DBPlanet = { + _id: planetId, + owner: user._id, + name: `${username}'s home planet`, + fields: 100, + buildings: [], + ships: [], + resources: [] + } - Astro.cookies.set("userid", user._id?.toString() as string, { + await createPlanet(planetData); + + const systemData: DBSystem = { + _id: new ObjectId(), + name: `${username}'s home system`, + ownedBy: user._id, + structures: [], + planets: [planetData._id], + } + + await createSystem(systemData); + + const galaxies = await getAllGalaxies(); + const sectorId = galaxies[galaxyIndex].sectors[sectorIndex]; + + await addSystemToSector(sectorId, systemData._id); + + const cookieOptions: AstroCookieSetOptions = { path: "/", maxAge: sessionTime, sameSite: "lax", secure: true - }) + } + + Astro.cookies.set("sessionToken", token, cookieOptions); + Astro.cookies.set("username", username, cookieOptions); + Astro.cookies.set("userid", user._id.toString() as string, cookieOptions); + Astro.cookies.set("currentPlanet", planetData._id.toString(), cookieOptions); + Astro.cookies.set("currentSystem", systemData._id.toString(), cookieOptions); + + await locationManager.init(); return Astro.redirect("/game"); }