39 lines
1.8 KiB
TypeScript
39 lines
1.8 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
import { withAuth } from "@/lib/db";
|
|
import { hashToken, randomToken } from "./tokens";
|
|
import { tooManyAttempts } from "./throttle";
|
|
|
|
// Kalender-Abo (26.11.45): ein Link je Haushalt. Gespeichert wird nur der Hash;
|
|
// den Link sieht die Person einmal, danach nur „Neuen Link erzeugen“.
|
|
|
|
/** Neuen Link erzeugen; ein alter verliert damit seine Gültigkeit. */
|
|
export async function newCalendarToken(client: PoolClient, householdId: string, locale: string): Promise<string> {
|
|
const token = randomToken();
|
|
await client.query("update households set calendar_token_hash = $2, calendar_locale = $3 where id = $1", [householdId, hashToken(token), locale]);
|
|
return token;
|
|
}
|
|
|
|
export async function removeCalendarToken(client: PoolClient, householdId: string): Promise<void> {
|
|
await client.query("update households set calendar_token_hash = null where id = $1", [householdId]);
|
|
}
|
|
|
|
/**
|
|
* Haushalt zum Link, oder null. Fehlversuche bremsen je Adresse und gemeinsam,
|
|
* damit niemand Links durchprobiert; gültige Abrufe zählen nicht (Kalender
|
|
* fragen stündlich nach).
|
|
*/
|
|
export async function householdForCalendar(token: string, ip: string): Promise<{ id: string } | "tooMany" | null> {
|
|
return withAuth(async (c) => {
|
|
const blocked = await c.query<{ n: number }>(
|
|
"select count(*)::int as n from auth_attempts where key = any($1) and at > now() - interval '15 minutes'",
|
|
[[`cal:${ip}`]],
|
|
);
|
|
if ((blocked.rows[0]?.n ?? 0) > 20) return "tooMany";
|
|
const { rows } = await c.query<{ id: string }>("select id from households where calendar_token_hash = $1", [hashToken(token)]);
|
|
if (rows[0]) return rows[0];
|
|
if ((await tooManyAttempts(c, `cal:${ip}`, 20, 15)) || (await tooManyAttempts(c, "cal:*", 200, 15))) return "tooMany";
|
|
return null;
|
|
});
|
|
}
|