This commit is contained in:
2025-09-01 22:53:57 -04:00
parent b433a26fc6
commit fd342e7d47
24 changed files with 132 additions and 332 deletions

View File

@@ -4,9 +4,9 @@ import dayjs from "dayjs";
import { Elysia, t } from "elysia";
import { combine } from "kefir";
import Bus from "kefir-bus";
import db from "./db";
import { liveTable, WsIn, WsOut } from "./table";
import { err } from "./logging";
import { generateTokenAndKey, resolveToken, tokenExists } from "./human";
export const WS = Bus<
{
@@ -19,63 +19,23 @@ export const WS = Bus<
const api = new Elysia({ prefix: "/api" })
.post("/whoami", async ({ cookie: { token } }) => {
let human: Human | null;
if (
token.value == null ||
(human = await db.human.findUnique({
where: {
token: token.value,
},
})) == null
) {
human = await db.human.create({
data: {},
});
console.log("WHOAMI");
let key: string | undefined;
if (token.value == null || (key = resolveToken(token.value)) == null) {
const [newToken, newKey] = generateTokenAndKey();
token.set({
value: human.token,
value: newToken,
expires: dayjs().add(1, "year").toDate(),
httpOnly: true,
});
return newKey;
}
return human.key;
return key;
})
.derive(async ({ cookie: { token }, status }) => {
const humanKey = await db.human
.findUnique({
where: { token: token.value },
})
.then((human) => human?.key);
const humanKey = token.value && resolveToken(token.value);
return humanKey != null ? { humanKey } : status(401);
})
.post(
"/setName",
({ body: { name }, humanKey }) =>
db.human.update({
where: {
key: humanKey,
},
data: {
name,
},
}),
{
body: t.Object({
name: t.String(),
}),
}
)
.get("/profile", ({ humanKey, query: { otherHumanKey } }) =>
db.human
.findFirst({ where: { key: otherHumanKey ?? humanKey } })
.then((human) => {
if (human == null) {
return null;
}
const { token, ...safeProfile } = human;
return safeProfile;
})
)
.ws("/ws/:tableKey", {
body: WsIn,
response: WsOut,