Skip to content
Snippets Groups Projects
Commit 2303acfd authored by Levatax's avatar Levatax
Browse files

feat: protect registration using hcaptcha

parent d7d6db1b
Branches
Tags
1 merge request!3Upgrade to Fiber v3 and implement hCaptcha protection
......@@ -2,3 +2,5 @@ ALLOWED_ORIGINS=https://hizla.io
DB=db
VERBOSE=1
LISTEN_ADDR=127.0.0.1:3000
HCAPTCHA_SITE_KEY=unset
HCAPTCHA_SECRET=unset
\ No newline at end of file
......@@ -36,10 +36,8 @@ func serve(sig chan os.Signal, db *leveldb.DB) error {
// /register
routeRegister(app, db)
// Graceful shutdown
app.Use(func(c fiber.Ctx) error {
return c.Next()
})
// /hcaptcha-site-key
routeHCaptchaSiteKey(app)
// graceful shutdown
go func() {
......
......@@ -9,6 +9,8 @@ const (
dbPath uint8 = iota
listenAddr
allowedOrigins
hCaptchaSecret
hCaptchaSiteKey
verboseLogging
confLen
)
......@@ -18,6 +20,8 @@ var confEnv = [confLen][2]string{
{"DB", "db"},
{"LISTEN_ADDR", "127.0.0.1:3000"},
{"ALLOWED_ORIGINS", "https://hizla.io"},
{"HCAPTCHA_SECRET", "unset"},
{"HCAPTCHA_SITE_KEY", "unset"},
{"VERBOSE", "1"},
}
......
......@@ -4,6 +4,7 @@ import (
"log"
"regexp"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/contrib/hcaptcha"
"github.com/syndtr/goleveldb/leveldb"
)
......@@ -13,9 +14,27 @@ type registration struct {
Email string `json:"email"`
}
// Middleware to conditionally apply hCaptcha
func conditionalCaptcha(captcha fiber.Handler) fiber.Handler {
return func(c fiber.Ctx) error {
if conf[hCaptchaSecret] == "unset" {
if verbose {
log.Printf("Captcha bypassed for %q", c.IP())
}
return c.Next()
}
return captcha(c)
}
}
// Waitlist registration route
func routeRegister(app *fiber.App, db *leveldb.DB) {
app.Post("/register", func(c fiber.Ctx) error {
captcha := hcaptcha.New(hcaptcha.Config{
SecretKey: conf[hCaptchaSecret],
})
app.Post("/register", conditionalCaptcha(captcha), func(c fiber.Ctx) error {
req := new(registration)
// Parse and validate the request
......@@ -67,3 +86,17 @@ func routeRegister(app *fiber.App, db *leveldb.DB) {
})
})
}
// Route to expose hCaptcha site key
func routeHCaptchaSiteKey(app *fiber.App) {
app.Get("/hcaptcha-site-key", func(c fiber.Ctx) error {
if conf[hCaptchaSiteKey] == "unset" {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"message": "hCaptcha site key not configured",
})
}
return c.JSON(fiber.Map{
"hcaptcha_site_key": conf[hCaptchaSiteKey],
})
})
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment