Bugfixing
This commit is contained in:
@@ -38,6 +38,3 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
|||||||
|
|
||||||
# Agents
|
# Agents
|
||||||
.claude/settings.local.json
|
.claude/settings.local.json
|
||||||
|
|
||||||
# Local test media for seed scripts
|
|
||||||
apps/api/src/scripts/fixtures
|
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Local test media for seed scripts
|
||||||
|
src/scripts/test-verification-media
|
||||||
@@ -2,18 +2,20 @@ import Elysia, { NotFoundError, t } from "elysia";
|
|||||||
import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain";
|
import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain";
|
||||||
import { authPlugin } from "../plugins/auth";
|
import { authPlugin } from "../plugins/auth";
|
||||||
import { s } from "../services";
|
import { s } from "../services";
|
||||||
import { BigIntIdSchema } from "../util/models";
|
import { AccountIdSchema, BigIntIdSchema } from "../util/models";
|
||||||
|
|
||||||
const AssessmentsController = new Elysia({ prefix: "/assessments" })
|
const AssessmentsController = new Elysia({ prefix: "/assessments" })
|
||||||
.use(authPlugin)
|
.use(authPlugin)
|
||||||
.guard({ authAdmin: true })
|
.guard({ authAdmin: true })
|
||||||
.post("/", async ({ body: { player, activityPerformances, id } }) => {
|
.post("/", async ({ body: { player, activityPerformances, accountId } }) => {
|
||||||
return await s.Assessments.create(player, activityPerformances, id);
|
const account = await s.Accounts.get(accountId);
|
||||||
|
if (!account) throw new NotFoundError("Account not found");
|
||||||
|
return await s.Assessments.create(player, activityPerformances, account.id);
|
||||||
}, {
|
}, {
|
||||||
body: t.Object({
|
body: t.Object({
|
||||||
player: PlayerSchema,
|
player: PlayerSchema,
|
||||||
activityPerformances: t.Array(ActivityPerformanceSchema),
|
activityPerformances: t.Array(ActivityPerformanceSchema),
|
||||||
id: t.Optional(t.String()),
|
accountId: AccountIdSchema,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ const AuthController = new Elysia({ prefix: "/auth" })
|
|||||||
.post("/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
|
.post("/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => {
|
||||||
const account = await s.Accounts.getByEmail(email);
|
const account = await s.Accounts.getByEmail(email);
|
||||||
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
|
const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH);
|
||||||
if (!account || !password_match) throw new UnauthorizedError("Invalid credentials");
|
if (!account?.password_hash || !password_match) throw new UnauthorizedError("Invalid credentials");
|
||||||
|
|
||||||
auth.set({
|
auth.set({
|
||||||
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
||||||
@@ -62,9 +62,11 @@ const AuthController = new Elysia({ prefix: "/auth" })
|
|||||||
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
|
.get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => {
|
||||||
if (query.error) throw new BadRequestError(query.error_description ? `${query.error}: ${query.error_description}` : query.error);
|
if (query.error) throw new BadRequestError(query.error_description ? `${query.error}: ${query.error_description}` : query.error);
|
||||||
|
|
||||||
|
// Validate input
|
||||||
if (!query.state) throw new BadRequestError("No Discord OAuth2 state query parameter provided");
|
if (!query.state) throw new BadRequestError("No Discord OAuth2 state query parameter provided");
|
||||||
if (query.state !== authDiscord.value) throw new BadRequestError("Invalid Discord OAuth state");
|
if (query.state !== authDiscord.value) throw new BadRequestError("Invalid Discord OAuth state");
|
||||||
|
|
||||||
|
// Retrieve access token from discord
|
||||||
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -80,36 +82,38 @@ const AuthController = new Elysia({ prefix: "/auth" })
|
|||||||
});
|
});
|
||||||
if (!tokenRes.ok) {
|
if (!tokenRes.ok) {
|
||||||
const errorBody = await tokenRes.json().catch(() => null);
|
const errorBody = await tokenRes.json().catch(() => null);
|
||||||
throw new BadGatewayError(errorBody ?? "Discord token exchange failed");
|
throw new BadGatewayError(errorBody ? JSON.stringify(errorBody) : "Discord token exchange failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenResPayload = await tokenRes.json();
|
const tokenResPayload = await tokenRes.json();
|
||||||
Value.Assert(t.Object({ access_token: t.String() }), tokenResPayload);
|
Value.Assert(t.Object({ access_token: t.String() }), tokenResPayload);
|
||||||
|
|
||||||
|
// Retrieve user's discord identity
|
||||||
const identityRes = await fetch("https://discord.com/api/users/@me", {
|
const identityRes = await fetch("https://discord.com/api/users/@me", {
|
||||||
headers: { "Authorization": `Bearer ${tokenResPayload.access_token}` }
|
headers: { "Authorization": `Bearer ${tokenResPayload.access_token}` }
|
||||||
});
|
});
|
||||||
if (!identityRes.ok) {
|
if (!identityRes.ok) {
|
||||||
const errorBody = await identityRes.json().catch(() => null);
|
const errorBody = await identityRes.json().catch(() => null);
|
||||||
throw new BadGatewayError(errorBody ?? "Failed to fetch Discord identity");
|
throw new BadGatewayError(errorBody ? JSON.stringify(errorBody) : "Failed to fetch Discord identity");
|
||||||
|
}
|
||||||
|
const discordIdentity = await identityRes.json();
|
||||||
|
Value.Assert(t.Object({ id: t.String(), email: t.Optional(t.Nullable(t.String())), username: t.String(), verified: t.Boolean() }), discordIdentity);
|
||||||
|
|
||||||
|
// Get account or create if it dosent exist
|
||||||
|
let account = await s.Accounts.get(`@${discordIdentity.id}`);
|
||||||
|
if (!account) {
|
||||||
|
// only accept VERIFIED emails not already used by another account
|
||||||
|
const email = discordIdentity.verified && discordIdentity.email ? discordIdentity.email : undefined;
|
||||||
|
const emailTaken = email !== undefined && !!(await s.Accounts.getByEmail(email));
|
||||||
|
account = await s.Accounts.create(
|
||||||
|
discordIdentity.id,
|
||||||
|
emailTaken ? undefined : email,
|
||||||
|
discordIdentity.username
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const identityResPayload = await identityRes.json();
|
// Setup and sign auth cookie
|
||||||
Value.Assert(t.Object({ id: t.String(), email: t.Optional(t.String()), username: t.String() }), identityResPayload);
|
|
||||||
|
|
||||||
// Create the account
|
|
||||||
let accountId = (await s.Accounts.get(`@${identityResPayload.id}`))?.id;
|
|
||||||
if (!accountId) {
|
|
||||||
accountId = (await s.Accounts.create(
|
|
||||||
identityResPayload.id,
|
|
||||||
identityResPayload.email,
|
|
||||||
identityResPayload.username
|
|
||||||
)).id;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Authenticate
|
|
||||||
auth.set({
|
auth.set({
|
||||||
value: await jwt.sign({ role: "user" satisfies AccountRole, sessionId: randomUUIDv7(), accountId, exp: JWT_EXP }),
|
value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }),
|
||||||
path: "/",
|
path: "/",
|
||||||
maxAge: JWT_EXP_SECONDS,
|
maxAge: JWT_EXP_SECONDS,
|
||||||
sameSite: env.NODE_ENV === "production" ? "lax" : "none",
|
sameSite: env.NODE_ENV === "production" ? "lax" : "none",
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import Elysia, { t } from "elysia";
|
import Elysia, { NotFoundError, t } from "elysia";
|
||||||
import { StandardsParamsSchema } from "@blade-and-brawn/calculator";
|
import { StandardsParamsSchema } from "@blade-and-brawn/calculator";
|
||||||
import { authPlugin } from "../plugins/auth";
|
import { authPlugin } from "../plugins/auth";
|
||||||
import { s } from "../services";
|
import { s } from "../services";
|
||||||
import { BigIntIdSchema } from "../util/models";
|
import { BigIntIdSchema } from "../util/models";
|
||||||
|
import { ConflictError } from "../util/error";
|
||||||
|
|
||||||
const StandardsController = new Elysia({ prefix: "/standards" })
|
const StandardsController = new Elysia({ prefix: "/standards" })
|
||||||
.use(authPlugin)
|
.use(authPlugin)
|
||||||
@@ -17,18 +18,25 @@ const StandardsController = new Elysia({ prefix: "/standards" })
|
|||||||
})
|
})
|
||||||
.group("/:id", (app) => app
|
.group("/:id", (app) => app
|
||||||
.get("/", async ({ params: { id } }) => {
|
.get("/", async ({ params: { id } }) => {
|
||||||
return await s.Standards.Configs.get(id);
|
const config = await s.Standards.Configs.get(id);
|
||||||
|
if (!config) throw new NotFoundError("Standards config not found");
|
||||||
|
return config;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.put("/", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => {
|
.put("/", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => {
|
||||||
await s.Standards.Configs.update(id, name, datasetId, parameters);
|
const activeConfig = await s.Calculator.Standards.Config.get();
|
||||||
|
if (activeConfig.id === id) throw new ConflictError("Cannot edit the active standards config");
|
||||||
|
const updated = await s.Standards.Configs.update(id, name, datasetId, parameters);
|
||||||
|
if (!updated) throw new NotFoundError("Standards config not found");
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||||
})
|
})
|
||||||
.delete("/", async ({ params: { id } }) => {
|
.delete("/", async ({ params: { id } }) => {
|
||||||
await s.Standards.Configs.delete(id);
|
if (await s.Standards.Configs.count() <= 1) throw new ConflictError("Cannot delete the last remaining standards config");
|
||||||
|
const deleted = await s.Standards.Configs.delete(id);
|
||||||
|
if (!deleted) throw new NotFoundError("Standards config not found");
|
||||||
}, { params: t.Object({ id: BigIntIdSchema }) })
|
}, { params: t.Object({ id: BigIntIdSchema }) })
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -38,12 +46,15 @@ const StandardsController = new Elysia({ prefix: "/standards" })
|
|||||||
})
|
})
|
||||||
.group("/:id", (app) => app
|
.group("/:id", (app) => app
|
||||||
.get("/", async ({ params: { id } }) => {
|
.get("/", async ({ params: { id } }) => {
|
||||||
return await s.Standards.Datasets.get(id);
|
const dataset = await s.Standards.Datasets.get(id);
|
||||||
|
if (!dataset) throw new NotFoundError("Standards dataset not found");
|
||||||
|
return dataset;
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema })
|
params: t.Object({ id: BigIntIdSchema })
|
||||||
})
|
})
|
||||||
.patch("/", async ({ params: { id }, body: { name } }) => {
|
.patch("/", async ({ params: { id }, body: { name } }) => {
|
||||||
await s.Standards.Datasets.update(id, name);
|
const updated = await s.Standards.Datasets.update(id, name);
|
||||||
|
if (!updated) throw new NotFoundError("Standards dataset not found");
|
||||||
}, {
|
}, {
|
||||||
params: t.Object({ id: BigIntIdSchema }),
|
params: t.Object({ id: BigIntIdSchema }),
|
||||||
body: t.Object({ name: t.String() })
|
body: t.Object({ name: t.String() })
|
||||||
|
|||||||
BIN
Binary file not shown.
Binary file not shown.
@@ -22,7 +22,7 @@ export class AccountsService {
|
|||||||
name: name ?? "",
|
name: name ?? "",
|
||||||
email: email ?? null
|
email: email ?? null
|
||||||
})
|
})
|
||||||
.returning("id")
|
.returning(["id", "discord_id", "name", "email", "gender", "role"])
|
||||||
.executeTakeFirstOrThrow();
|
.executeTakeFirstOrThrow();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -64,6 +64,9 @@ class CalculatorStandardsConfigService {
|
|||||||
config: null as StandardsConfig | null
|
config: null as StandardsConfig | null
|
||||||
},
|
},
|
||||||
isStale: async () => {
|
isStale: async () => {
|
||||||
|
// Becomes stale only when standards are switched
|
||||||
|
// We currently enforce read-only view of selected calculator's standards config
|
||||||
|
// So only way to update calculator is to make new standards config, edit, then switch
|
||||||
const { standards_config_id: selectedConfigId } = await db.selectFrom("calculators")
|
const { standards_config_id: selectedConfigId } = await db.selectFrom("calculators")
|
||||||
.select("standards_config_id")
|
.select("standards_config_id")
|
||||||
.where("name", "=", this.name)
|
.where("name", "=", this.name)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ class StandardsConfigService {
|
|||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(id: string): Promise<StandardsConfig & { id: string, name: string, datasetId: string }> {
|
async get(id: string): Promise<(StandardsConfig & { id: string, name: string, datasetId: string }) | undefined> {
|
||||||
const result = await db.selectFrom("standards_configs")
|
const result = await db.selectFrom("standards_configs")
|
||||||
.innerJoin("standards_datasets", "standards_datasets.id", "standards_configs.dataset_id")
|
.innerJoin("standards_datasets", "standards_datasets.id", "standards_configs.dataset_id")
|
||||||
.select([
|
.select([
|
||||||
@@ -42,7 +42,8 @@ class StandardsConfigService {
|
|||||||
"standards_datasets.data as data",
|
"standards_datasets.data as data",
|
||||||
])
|
])
|
||||||
.where("standards_configs.id", "=", id)
|
.where("standards_configs.id", "=", id)
|
||||||
.executeTakeFirstOrThrow({ errorConstructor: () => new Error(`No config with id "${id}"`) });
|
.executeTakeFirst();
|
||||||
|
if (!result) return;
|
||||||
Value.Assert(StandardsParamsSchema, result.params);
|
Value.Assert(StandardsParamsSchema, result.params);
|
||||||
Value.Assert(StandardsDataSchema, result.data);
|
Value.Assert(StandardsDataSchema, result.data);
|
||||||
return {
|
return {
|
||||||
@@ -54,24 +55,26 @@ class StandardsConfigService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(id: string, name: string, datasetId: string, params: StandardsParams) {
|
async update(id: string, name: string, datasetId: string, params: StandardsParams): Promise<boolean> {
|
||||||
const result = await db.updateTable("standards_configs")
|
const result = await db.updateTable("standards_configs")
|
||||||
.set({ name, params, dataset_id: datasetId })
|
.set({ name, params, dataset_id: datasetId })
|
||||||
.where("id", "=", id)
|
.where("id", "=", id)
|
||||||
.execute();
|
.executeTakeFirst();
|
||||||
if (result[0]?.numUpdatedRows === 0n) throw new Error(`No config with id "${id}"`);
|
return result.numUpdatedRows > 0n;
|
||||||
}
|
}
|
||||||
|
|
||||||
async delete(id: string) {
|
async count(): Promise<number> {
|
||||||
const { count } = await db.selectFrom("standards_configs")
|
const { count } = await db.selectFrom("standards_configs")
|
||||||
.select(db.fn.countAll<number>().as("count"))
|
.select(db.fn.countAll<number>().as("count"))
|
||||||
.executeTakeFirstOrThrow();
|
.executeTakeFirstOrThrow();
|
||||||
if (Number(count) <= 1) throw new Error("Cannot delete the last remaining standards configuration");
|
return Number(count);
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string): Promise<boolean> {
|
||||||
const result = await db.deleteFrom("standards_configs")
|
const result = await db.deleteFrom("standards_configs")
|
||||||
.where("id", "=", id)
|
.where("id", "=", id)
|
||||||
.execute();
|
.executeTakeFirst();
|
||||||
if (result[0]?.numDeletedRows === 0n) throw new Error(`No config with id "${id}"`);
|
return result.numDeletedRows > 0n;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,20 +86,21 @@ class StandardsDatasetService {
|
|||||||
.execute();
|
.execute();
|
||||||
}
|
}
|
||||||
|
|
||||||
async get(id: string): Promise<{ id: string, name: string, data: StandardsData }> {
|
async get(id: string): Promise<{ id: string, name: string, data: StandardsData } | undefined> {
|
||||||
const result = await db.selectFrom("standards_datasets")
|
const result = await db.selectFrom("standards_datasets")
|
||||||
.select(["id", "name", "data"])
|
.select(["id", "name", "data"])
|
||||||
.where("id", "=", id)
|
.where("id", "=", id)
|
||||||
.executeTakeFirstOrThrow({ errorConstructor: () => new Error(`No dataset with id "${id}"`) });
|
.executeTakeFirst();
|
||||||
|
if (!result) return;
|
||||||
Value.Assert(StandardsDataSchema, result.data);
|
Value.Assert(StandardsDataSchema, result.data);
|
||||||
return { id: result.id, name: result.name, data: result.data };
|
return { id: result.id, name: result.name, data: result.data };
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(id: string, name: string) {
|
async update(id: string, name: string): Promise<boolean> {
|
||||||
const result = await db.updateTable("standards_datasets")
|
const result = await db.updateTable("standards_datasets")
|
||||||
.set({ name })
|
.set({ name })
|
||||||
.where("id", "=", id)
|
.where("id", "=", id)
|
||||||
.execute();
|
.executeTakeFirst();
|
||||||
if (result[0]?.numUpdatedRows === 0n) throw new Error(`No dataset with id "${id}"`);
|
return result.numUpdatedRows > 0n;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user