Skip to content

Commit 6ce7f4c

Browse files
committed
add rate limiting
1 parent c7f60d4 commit 6ce7f4c

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/routes/admin/login/+page.server.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,40 @@ import { ADMIN_PAGE_PASSWORD } from '$env/static/private'
22
import { fail, redirect } from '@sveltejs/kit'
33
import type { Actions } from './$types'
44
import { create_session } from '../sessions'
5+
import { redis } from '$lib/server/redis'
56

67
export const prerender = false
78

89
export const actions: Actions = {
910
login: async (event) => {
11+
const ip = event.getClientAddress()
12+
const key = `rate_limit_admin_login:ip:${ip}`
13+
const count = Number((await redis.get(key)) ?? 0)
14+
15+
if (count >= 5) {
16+
return fail(429, {
17+
error: 'Too many login attempts. Please try again later.',
18+
})
19+
}
20+
1021
const form = await event.request.formData()
1122
const password = form.get('password')
1223

13-
if (!password) {
24+
if (!password || typeof password !== 'string') {
1425
return fail(400, { error: 'Password required' })
1526
}
27+
1628
if (password !== ADMIN_PAGE_PASSWORD) {
29+
const next = await redis.incr(key)
30+
if (next === 1) await redis.expire(key, 60 * 10)
31+
1732
return fail(400, { error: 'Password incorrect' })
1833
}
1934

2035
create_session(event)
2136

37+
await redis.del(key)
38+
2239
redirect(303, '/admin')
2340
},
2441
}

0 commit comments

Comments
 (0)