3x-ui/web/service/turnstile.go
Sora39831 5f83415e95 feat: add user registration with role-based access
- Add Role field to User model (admin/user) with uniqueIndex on Username
- Add POST /register endpoint with optional Cloudflare Turnstile verification
- Add RegisterUser service with bcrypt password hashing and duplicate detection
- Set default admin user role to "admin", new registrations get "user"
- Add turnstileSecretKey setting and GetTurnstileSecretKey getter
- Add i18n keys (userExists, errorRegister) to all 13 translation files
2026-04-02 23:49:30 +08:00

44 lines
884 B
Go

package service
import (
"encoding/json"
"io"
"net/http"
"net/url"
"time"
)
const turnstileVerifyURL = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
type turnstileResponse struct {
Success bool `json:"success"`
}
// VerifyTurnstile verifies a Cloudflare Turnstile token with the given secret key.
func VerifyTurnstile(secretKey, token, remoteIP string) bool {
form := url.Values{
"secret": {secretKey},
"response": {token},
}
if remoteIP != "" {
form.Set("remoteip", remoteIP)
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.PostForm(turnstileVerifyURL, form)
if err != nil {
return false
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
var result turnstileResponse
if err := json.Unmarshal(body, &result); err != nil {
return false
}
return result.Success
}