forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlockout.ts
More file actions
59 lines (53 loc) · 1.81 KB
/
lockout.ts
File metadata and controls
59 lines (53 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// src/lib/lockout.ts
//
// Functions: checkLockout, recordFailedAttempt, resetFailedAttempts
import { eq, sql } from "drizzle-orm"
import { NextResponse } from "next/server"
import { db } from "@/lib/db"
import { appSettings } from "@/lib/db/schema"
interface LockoutSettings {
lockoutEnabled: boolean
lockoutThreshold: number
lockoutDurationMinutes: number
lockedUntil: Date | null
}
export function checkLockout(settings: LockoutSettings): NextResponse | null {
if (!settings.lockoutEnabled) return null
if (!settings.lockedUntil || settings.lockedUntil <= new Date()) return null
const retryAfter = Math.ceil((settings.lockedUntil.getTime() - Date.now()) / 1000)
return NextResponse.json(
{ error: "Too many failed attempts. Try again later.", retryAfter },
{ status: 429, headers: { "Retry-After": String(retryAfter) } }
)
}
export async function recordFailedAttempt(
settingsId: number,
lockoutSettings: {
lockoutEnabled: boolean
lockoutThreshold: number
lockoutDurationMinutes: number
}
): Promise<void> {
const [updated] = await db
.update(appSettings)
.set({ failedLoginAttempts: sql`${appSettings.failedLoginAttempts} + 1` })
.where(eq(appSettings.id, settingsId))
.returning({ failedLoginAttempts: appSettings.failedLoginAttempts })
if (
lockoutSettings.lockoutEnabled &&
updated.failedLoginAttempts >= lockoutSettings.lockoutThreshold
) {
await db
.update(appSettings)
.set({
lockedUntil: new Date(Date.now() + lockoutSettings.lockoutDurationMinutes * 60_000),
})
.where(eq(appSettings.id, settingsId))
}
}
export async function resetFailedAttempts(settingsId: number): Promise<void> {
await db
.update(appSettings)
.set({ failedLoginAttempts: 0, lockedUntil: null })
.where(eq(appSettings.id, settingsId))
}