-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLoginThrottleMiddleware.swift
More file actions
45 lines (39 loc) · 1.37 KB
/
LoginThrottleMiddleware.swift
File metadata and controls
45 lines (39 loc) · 1.37 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
import Foundation
import Vapor
// MARK: - Login Throttle Middleware
struct LoginThrottleMiddleware: AsyncMiddleware {
func respond(
to request: Request,
chainingTo next: any AsyncResponder
) async throws -> Response {
let rules = request.configuration.throttle.login
guard rules.enabled else {
return try await next.respond(to: request)
}
let source = request.remoteAddress?.ipAddress ?? "unknown"
let bucket = Passage.Throttle.Bucket(
scope: .login,
dimension: .source(source),
enabled: rules.enabled,
)
let now = Date()
if case let .throttled(delay) = await request.throttle.check(
bucket: bucket, against: rules.perSource, at: now
) {
throw AuthenticationError.tooManyLoginAttempts(retryAfter: delay)
}
do {
let response = try await next.respond(to: request)
let code = Int(response.status.code)
if (200..<300).contains(code) {
await request.throttle.reset(bucket: bucket)
} else if code >= 400 {
await request.throttle.penalize(bucket: bucket, at: now)
}
return response
} catch {
await request.throttle.penalize(bucket: bucket, at: now)
throw error
}
}
}