18 lines
763 B
TypeScript
18 lines
763 B
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
|
|
/**
|
|
* Bremse gegen Durchprobieren. Vermerkt einen Versuch unter `key` und sagt,
|
|
* ob in den letzten `minutes` Minuten mehr als `limit` waren. Läuft in einer
|
|
* withAuth-Transaktion.
|
|
*/
|
|
export async function tooManyAttempts(client: PoolClient, key: string, limit: number, minutes: number): Promise<boolean> {
|
|
await client.query("delete from auth_attempts where at < now() - interval '1 day'");
|
|
await client.query("insert into auth_attempts (key) values ($1)", [key]);
|
|
const { rows } = await client.query<{ n: number }>(
|
|
"select count(*)::int as n from auth_attempts where key = $1 and at > now() - make_interval(mins => $2)",
|
|
[key, minutes],
|
|
);
|
|
return (rows[0]?.n ?? 0) > limit;
|
|
}
|