Fix register script

This commit is contained in:
Aelita4 2024-11-04 10:26:05 +01:00
parent a9e9c5b080
commit 8d34bfe64f
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
8 changed files with 92 additions and 74 deletions

View File

@ -10,6 +10,11 @@ export const getPlanetById = async (id: ObjectId) => {
return await (await Planets()).findOne({ _id: id }) as DBPlanet; 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<any>) => { export const updatePlanetResources = async (planetId: ObjectId, resources: Array<any>) => {
const planets = await Planets(); const planets = await Planets();
await planets.updateOne({ _id: planetId }, { await planets.updateOne({ _id: planetId }, {

View File

@ -11,3 +11,7 @@ export const getSectorById = async (id: ObjectId) => {
_id: id _id: id
}) as DBSector; }) as DBSector;
} }
export const addSystemToSector = async (sectorId: ObjectId, systemId: ObjectId) => {
return await (await Sectors()).updateOne({ _id: sectorId }, { $push: { systems: systemId } });
}

View File

@ -12,6 +12,11 @@ export const getSystemById = async (id: ObjectId) => {
}) as DBSystem; }) 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 }>) => { export const updateSystemStructures = async (systemId: ObjectId, structures: Array<{ id: string, level: number }>) => {
const systems = await Systems(); const systems = await Systems();
await systems.updateOne({ _id: systemId }, { await systems.updateOne({ _id: systemId }, {

View File

@ -10,8 +10,9 @@ export const getAllUsers = async () => {
return users.find({}).toArray() as Promise<DBUser[]>; return users.find({}).toArray() as Promise<DBUser[]>;
} }
export const createUser = async (username: string, email: string, password: string) => { export const createUser = async (id: ObjectId, username: string, email: string, password: string, mainPlanet: ObjectId) => {
const user = { const user: DBUser = {
_id: id,
username, username,
email, email,
password: await hash(password), password: await hash(password),
@ -19,13 +20,11 @@ export const createUser = async (username: string, email: string, password: stri
createdAt: new Date(), createdAt: new Date(),
updatedAt: new Date(), updatedAt: new Date(),
research: [], research: [],
mainPlanet
} }
await (await Users()).insertOne(user); await (await Users()).insertOne(user);
const newUser = await getUserByNickOrEmail(username); return user;
if(!newUser) return user;
return newUser;
} }
export const deleteUser = async (id: ObjectId) => { export const deleteUser = async (id: ObjectId) => {

View File

@ -60,18 +60,18 @@ export const POST: APIRoute = async({ request }) => {
const tokenString = `A.${timestamp}.${userEncoded}.${random}`; const tokenString = `A.${timestamp}.${userEncoded}.${random}`;
const user = locationManager.getUser(userFromDb._id); // const user = locationManager.getUser(userFromDb._id);
if(!user) return new Response( // if(!user) return new Response(
JSON.stringify({ // JSON.stringify({
code: 404, // code: 404,
message: "Not found", // message: "Not found",
error: `User ${data.username} not found` // error: `User ${data.username} not found`
}), { status: 404 } // }), { status: 404 }
) // )
const accessToken: AccessToken = { const accessToken: AccessToken = {
type: "A", type: "A",
user, user: userFromDb,
entropy: randomHashed.toString(), entropy: randomHashed.toString(),
createdAt: now, createdAt: now,
expiresAt: new Date(now.getTime() + expiresIn), expiresAt: new Date(now.getTime() + expiresIn),

View File

@ -13,12 +13,12 @@ if(loggedToken === null || username === "") return Astro.redirect('/logout');
const checkUser = await getUserByAccessToken(loggedToken); const checkUser = await getUserByAccessToken(loggedToken);
if(checkUser === null || checkUser.username !== username) return Astro.redirect('/logout'); 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; const currentPlanetId = Astro.cookies.get('currentPlanet')?.value ?? null;
if(currentPlanetId === null) return Astro.redirect('/logout');
const currentPlanet = locationManager.getPlanet(new ObjectId(currentPlanetId)); const currentPlanet = locationManager.getPlanet(new ObjectId(currentPlanetId));
if(currentPlanet === undefined) { if(currentPlanet === undefined) {
Astro.cookies.delete('planetid'); Astro.cookies.delete('planetid');
return Astro.redirect('/game/logout'); return Astro.redirect('/logout');
} }
--- ---

View File

@ -27,7 +27,7 @@ if(Astro.request.method === "POST") {
if(!user) throw new Error("User not found"); if(!user) throw new Error("User not found");
const sessionTime = config.SESSION_TIME_MINUTES * 60; 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', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
username, username,

View File

@ -1,10 +1,19 @@
--- ---
import Layout from '../layouts/Layout.astro';
import NavBar from '../components/NavBar.astro'; import NavBar from '../components/NavBar.astro';
import Layout from '../layouts/Layout.astro';
import { createUser } from '../lib/db/users'; import { createUser } from '../lib/db/users';
import { AstroCookieSetOptions } from 'astro';
import { ObjectId } from 'mongodb';
import config from '../../config.json'; 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 = ""; let error = "";
@ -15,52 +24,24 @@ if(Astro.request.method === "POST") {
const password = data.get("password") as string | ""; const password = data.get("password") as string | "";
const password2 = data.get("password2") as string | ""; const password2 = data.get("password2") as string | "";
if(username === "") { if(username === "") error = "username is required";
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";
Astro.redirect("/register"); 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(email === "") { if(password2 === "") error = "password2 is required";
error = "email is required"; 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";
}
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(error === "") { 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 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', method: 'POST',
body: JSON.stringify({ body: JSON.stringify({
username, username,
@ -75,26 +56,50 @@ if(Astro.request.method === "POST") {
const token = (await res.json()).accessToken; const token = (await res.json()).accessToken;
Astro.cookies.set("sessionToken", token, { const galaxyIndex = Math.floor(Math.random() * 4);
path: "/", const sectorIndex = Math.floor(Math.random() * 8);
maxAge: sessionTime,
sameSite: "lax",
secure: true
});
Astro.cookies.set("username", username, { const planetData: DBPlanet = {
path: "/", _id: planetId,
maxAge: sessionTime, owner: user._id,
sameSite: "lax", name: `${username}'s home planet`,
secure: true 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: "/", path: "/",
maxAge: sessionTime, maxAge: sessionTime,
sameSite: "lax", sameSite: "lax",
secure: true 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"); return Astro.redirect("/game");
} }