支持 Cloudflare Turnstile 的 CAPTCHA
Cloudflare Turnstile 是一个友好、免费的 CAPTCHA 替代品,它可以与 Supabase Edge Functions 无缝协作,保护你的表单。在 GitHub 上查看。
设置 #
🌐 Setup
- 按照这些步骤来设置一个新站点:https://developers.cloudflare.com/turnstile/get-started/
- 将 Cloudflare Turnstile 小部件添加到你的网站:https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/
代码 #
🌐 Code
在你的项目中创建一个新函数:
🌐 Create a new function in your project:
supabase functions new cloudflare-turnstile然后把代码加到 index.ts 文件里:
🌐 And add the code to the index.ts file:
import { withSupabase } from 'npm:@supabase/server@^1'console.log('Hello from Cloudflare Trunstile!')function ips(req: Request) { return req.headers.get('x-forwarded-for')?.split(/\s*,\s*/)}// `withSupabase` handles CORS and preflight requests for you.export default { fetch: withSupabase({ auth: 'none' }, async (req) => { const { token } = await req.json() const clientIps = ips(req) || [''] const ip = clientIps[0] // Validate the token by calling the // "/siteverify" API endpoint. let formData = new FormData() formData.append('secret', Deno.env.get('CLOUDFLARE_SECRET_KEY') ?? '') formData.append('response', token) formData.append('remoteip', ip) const url = 'https://challenges.cloudflare.com/turnstile/v0/siteverify' const result = await fetch(url, { body: formData, method: 'POST', }) const outcome = await result.json() console.log(outcome) if (outcome.success) { return Response.json({ success: true }) } return Response.json({ success: false }) }),}部署服务器端验证的 Edge Functions #
🌐 Deploy the server-side validation Edge Functions
supabase functions deploy cloudflare-turnstile --no-verify-jwtsupabase secrets set CLOUDFLARE_SECRET_KEY=your_secret_key从你的网站调用这个函数 #
🌐 Invoke the function from your site
const { data, error } = await supabase.functions.invoke('cloudflare-turnstile', { body: { token },})