Fix register script
This commit is contained in:
parent
a9e9c5b080
commit
8d34bfe64f
|
@ -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<any>) => {
|
||||
const planets = await Planets();
|
||||
await planets.updateOne({ _id: planetId }, {
|
||||
|
|
|
@ -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 } });
|
||||
}
|
|
@ -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 }, {
|
||||
|
|
|
@ -10,8 +10,9 @@ export const getAllUsers = async () => {
|
|||
return users.find({}).toArray() as Promise<DBUser[]>;
|
||||
}
|
||||
|
||||
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) => {
|
||||
|
|
|
@ -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),
|
||||
|
|
|
@ -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');
|
||||
}
|
||||
---
|
||||
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue