Skip to content

Integrate Cloudflare Turnstile for Enhanced Security #2

@TheBoatyMcBoatFace

Description

@TheBoatyMcBoatFace

Description

We need to integrate Cloudflare Turnstile (a CAPTCHA alternative) on key pages where non-authenticated users submit information (e.g., login, registration, and password reset) to enhance security and prevent spam.

Tasks

  1. Set Up Environment Variables

    • Ensure the following environment variables are set:
      • CLOUDFLARE_TURNSTYLE_SITE_KEY=SiteKey
      • CLOUDFLARE_TURNSTYLE_SECRET_KEY=SecretKey
  2. Update Templates

    • Add the Cloudflare Turnstile widget to the login, registration, and password reset templates.
      <div class="cf-turnstile" data-sitekey="{{ site_key }}"></div>
      <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
  3. Verify Turnstile in Routes

    • Implement server-side verification of Turnstile in the corresponding form handling routes.
      import requests
      from flask import request, flash
      
      def verify_turnstile(response_token):
          secret_key = os.getenv('CLOUDFLARE_TURNSTYLE_SECRET_KEY')
          data = {
              'secret': secret_key,
              'response': response_token
          }
          verify_url = "https://challenges.cloudflare.com/turnstile/v0/siteverify"
          response = requests.post(verify_url, data=data)
          return response.json().get('success', False)
      
      @auth_bp.route('/login', methods=['GET', 'POST'])
      def login():
          # Existing code...
          if form.validate_on_submit():
              turnstile_response = request.form.get('cf-turnstile-response')
              if not verify_turnstile(turnstile_response):
                  flash('Invalid CAPTCHA. Please try again.', 'danger')
                  return render_template('auth/login.html', form=form)
              # Continue with login logic...
  4. Test Integration

    • Verify the Turnstile integration to ensure it prevents spam submissions and does not obstruct valid users.

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions