Skip to content

Commit 5950a99

Browse files
committed
Improve the captcha verification
1 parent fcf1ac0 commit 5950a99

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed
Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,42 @@
11
package org.komputing.fauceth
22

3-
import java.net.URI
4-
import java.net.http.HttpClient
5-
import java.net.http.HttpRequest
6-
import java.net.http.HttpResponse
3+
import kotlinx.coroutines.delay
4+
import okhttp3.*
5+
import java.io.IOException
76
import java.time.Duration
87

98
// very crude for now
10-
fun verifyCaptcha(hCaptchaResponse: String, hCaptchaSecret: String): Boolean {
11-
val body = "response=$hCaptchaResponse&secret=$hCaptchaSecret"
9+
suspend fun verifyCaptcha(hCaptchaResponse: String, hCaptchaSecret: String): Boolean {
1210

13-
val httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()
11+
val client = OkHttpClient.Builder()
12+
.connectTimeout(Duration.ofSeconds(5))
13+
.readTimeout(Duration.ofSeconds(10))
14+
.build()
1415

15-
val request = HttpRequest.newBuilder()
16-
.uri(URI.create("https://hcaptcha.com/siteverify"))
16+
val request = Request.Builder()
17+
.url("https://hcaptcha.com/siteverify")
1718
.header("Content-Type", "application/x-www-form-urlencoded")
18-
.timeout(Duration.ofSeconds(10))
19-
.POST(HttpRequest.BodyPublishers.ofString(body)).build()
19+
.post(FormBody.Builder().add("response", hCaptchaResponse).add("secret", hCaptchaSecret).build())
20+
.build()
2021

21-
val response = httpClient.send(request, HttpResponse.BodyHandlers.ofString())
2222

23-
return response.statusCode() == 200 && response.body().contains("\"success\":true")
23+
var attempts = 0
24+
25+
while (true) {
26+
27+
try {
28+
val response = client.newCall(request).execute()
29+
if (response.code == 200) {
30+
return (response.body?.string()?.contains("\"success\":true") == true)
31+
}
32+
} catch (ioe: IOException) {
33+
// can happen - we will retry
34+
}
35+
36+
if (attempts == 3) return false
37+
38+
attempts++
39+
delay(500L * attempts)
40+
}
41+
2442
}

0 commit comments

Comments
 (0)