#!/usr/bin/env python3 """ Cloudflare Credentials Setup Web Interface Provides a web UI to configure Cloudflare API credentials """ import os import json import subprocess import re from pathlib import Path from flask import Flask, render_template_string, request, jsonify, redirect, url_for app = Flask(__name__) SCRIPT_DIR = Path(__file__).parent.parent ENV_FILE = SCRIPT_DIR / ".env" # HTML Template HTML_TEMPLATE = """ Cloudflare Credentials Setup

๐Ÿ” Cloudflare Setup

Configure your Cloudflare API credentials

{% if message %}
{{ message }}
{% endif %}

Current Status

Email: {{ current_email or 'Not set' }}
API Key: {{ 'Set' if has_api_key else 'Not set' }}
API Token: {{ 'Set' if has_api_token else 'Not set' }}
Account ID:
Zone ID: {{ current_zone_id or 'Not set' }}
Domain: {{ current_domain or 'Not set' }}
Your Cloudflare account email address
Create API Token (Recommended - more secure)
Your Cloudflare account ID
DNS zone ID for your domain
Your domain name (e.g., d-bis.org)
Cloudflare Tunnel service token
""" def load_env(): """Load current .env file values""" env_vars = {} if ENV_FILE.exists(): with open(ENV_FILE, 'r') as f: for line in f: line = line.strip() if line and not line.startswith('#') and '=' in line: key, value = line.split('=', 1) key = key.strip() value = value.strip().strip('"').strip("'") env_vars[key] = value return env_vars def save_env(env_vars): """Save environment variables to .env file""" # Read existing file to preserve comments and structure lines = [] if ENV_FILE.exists(): with open(ENV_FILE, 'r') as f: lines = f.readlines() # Update or add variables updated_keys = set() new_lines = [] for line in lines: stripped = line.strip() if stripped and not stripped.startswith('#') and '=' in stripped: key = stripped.split('=', 1)[0].strip() if key in env_vars: new_lines.append(f'{key}="{env_vars[key]}"\n') updated_keys.add(key) continue new_lines.append(line) # Add new variables for key, value in env_vars.items(): if key not in updated_keys: new_lines.append(f'{key}="{value}"\n') with open(ENV_FILE, 'w') as f: f.writelines(new_lines) def test_api_credentials(email, api_key, api_token): """Test Cloudflare API credentials""" import requests headers = {"Content-Type": "application/json"} if api_token: headers["Authorization"] = f"Bearer {api_token}" url = "https://api.cloudflare.com/client/v4/user" elif api_key and email: headers["X-Auth-Email"] = email headers["X-Auth-Key"] = api_key url = "https://api.cloudflare.com/client/v4/user" else: return False, "No credentials provided" try: response = requests.get(url, headers=headers, timeout=10) data = response.json() if data.get('success'): user_email = data.get('result', {}).get('email', '') return True, f"โœ“ Authentication successful! Logged in as: {user_email}" else: error = data.get('errors', [{}])[0].get('message', 'Unknown error') return False, f"โœ— Authentication failed: {error}" except Exception as e: return False, f"โœ— Connection error: {str(e)}" @app.route('/') def index(): """Display the setup form""" env = load_env() return render_template_string(HTML_TEMPLATE, current_email=env.get('CLOUDFLARE_EMAIL', ''), has_api_key=bool(env.get('CLOUDFLARE_API_KEY', '')), has_api_token=bool(env.get('CLOUDFLARE_API_TOKEN', '')), current_account_id=env.get('CLOUDFLARE_ACCOUNT_ID', ''), current_zone_id=env.get('CLOUDFLARE_ZONE_ID', ''), current_domain=env.get('CLOUDFLARE_DOMAIN', ''), message=request.args.get('message', ''), message_type=request.args.get('type', 'info') ) @app.route('/save', methods=['POST']) def save(): """Save credentials to .env file""" env = load_env() # Update only provided fields if request.form.get('email'): env['CLOUDFLARE_EMAIL'] = request.form.get('email') if request.form.get('api_key'): env['CLOUDFLARE_API_KEY'] = request.form.get('api_key') if request.form.get('api_token'): env['CLOUDFLARE_API_TOKEN'] = request.form.get('api_token') # Remove API key if token is provided if 'CLOUDFLARE_API_KEY' in env: del env['CLOUDFLARE_API_KEY'] if request.form.get('account_id'): env['CLOUDFLARE_ACCOUNT_ID'] = request.form.get('account_id') if request.form.get('zone_id'): env['CLOUDFLARE_ZONE_ID'] = request.form.get('zone_id') if request.form.get('domain'): env['CLOUDFLARE_DOMAIN'] = request.form.get('domain') if request.form.get('tunnel_token'): env['CLOUDFLARE_TUNNEL_TOKEN'] = request.form.get('tunnel_token') save_env(env) return redirect(url_for('index', message='Credentials saved successfully!', type='success')) @app.route('/test', methods=['POST']) def test(): """Test API credentials""" env = load_env() email = request.form.get('email') or env.get('CLOUDFLARE_EMAIL', '') api_key = request.form.get('api_key') or env.get('CLOUDFLARE_API_KEY', '') api_token = request.form.get('api_token') or env.get('CLOUDFLARE_API_TOKEN', '') if not email and not api_token: return redirect(url_for('index', message='Please provide email and API key, or API token', type='error')) success, message = test_api_credentials(email, api_key, api_token) return redirect(url_for('index', message=message, type='success' if success else 'error')) if __name__ == '__main__': print("\n" + "="*60) print("๐ŸŒ Cloudflare Credentials Setup Web Interface") print("="*60) print(f"\n๐Ÿ“ .env file location: {ENV_FILE}") print(f"\n๐Ÿ”— Open in your browser:") print(f" http://localhost:5000") print(f" http://127.0.0.1:5000") print(f"\nโš ๏ธ This server is only accessible from localhost") print(f" Press Ctrl+C to stop the server\n") print("="*60 + "\n") app.run(host='127.0.0.1', port=5000, debug=False)