Generator Public

Code #4634

Secret Code Generator API Endpoint

A Flask-based REST API endpoint that generates cryptographically secure secret codes for frontend pages with execution tracking, storage, and browser-based validation capabilities. Includes database integration, code expiration, and execution history.

Python
from flask import Flask, request, jsonify
from flask_cors import CORS
from datetime import datetime, timedelta
import secrets
import string
import sqlite3
import hashlib
import json
from functools import wraps

app = Flask(__name__)
CORS(app)

DB_FILE = 'secret_codes.db'

def init_database():
    '''Initialize SQLite database for storing secret codes and execution history'''
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS secret_codes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            code TEXT UNIQUE NOT NULL,
            page_identifier TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            expires_at TIMESTAMP NOT NULL,
            is_executed BOOLEAN DEFAULT 0,
            execution_count INTEGER DEFAULT 0
        )
    ''')
    
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS execution_history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            code_id INTEGER NOT NULL,
            executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            browser_info TEXT,
            ip_address TEXT,
            FOREIGN KEY (code_id) REFERENCES secret_codes(id)
        )
    ''')
    
    conn.commit()
    conn.close()

def generate_secret_code(length=32):
    '''Generate a cryptographically secure random code'''
    alphabet = string.ascii_letters + string.digits
    return ''.join(secrets.choice(alphabet) for i in range(length))

def get_client_ip():
    '''Extract client IP address from request'''
    if request.environ.get('HTTP_X_FORWARDED_FOR'):
        return request.environ.get('HTTP_X_FORWARDED_FOR').split(',')[0]
    return request.remote_addr

def save_secret_code(code, page_identifier, expiration_hours=24):
    '''Save generated code to database with expiration time'''
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    
    expires_at = datetime.now() + timedelta(hours=expiration_hours)
    
    try:
        cursor.execute('''
            INSERT INTO secret_codes (code, page_identifier, expires_at)
            VALUES (?, ?, ?)
        ''', (code, page_identifier, expires_at))
        conn.commit()
        code_id = cursor.lastrowid
        conn.close()
        return code_id
    except sqlite3.IntegrityError:
        conn.close()
        return None

def verify_code_exists(code):
    '''Verify if a code exists and is not expired'''
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT id, page_identifier, expires_at FROM secret_codes
        WHERE code = ? AND expires_at > datetime('now')
    ''', (code,))
    
    result = cursor.fetchone()
    conn.close()
    return result

def record_execution(code_id, browser_info):
    '''Record code execution in history and update execution count'''
    conn = sqlite3.connect(DB_FILE)
    cursor = conn.cursor()
    ip_address = get_client_ip()
    
    cursor.execute('''
        INSERT INTO execution_history (code_id, browser_info, ip_address)
        VALUES (?, ?, ?)
    ''', (code_id, browser_info, ip_address))
    
    cursor.execute('''
        UPDATE secret_codes SET execution_count = execution_count + 1, is_executed = 1
        WHERE id = ?
    ''', (code_id,))
    
    conn.commit()
    conn.close()

@app.route('/api/generate-code', methods=['POST'])
def generate_code_endpoint():
    '''
    Generate a new secret code for a specific frontend page.
    
    Expected JSON payload:
    {
        "page_identifier": "dashboard",
        "code_length": 32,
        "expiration_hours": 24
    }
    
    Returns: Secret code and metadata
    '''
    try:
        data = request.get_json()
        
        if not data or 'page_identifier' not in data:
            return jsonify({
                'success': False,
                'error': 'page_identifier is required'
            }), 400
        
        page_identifier = data.get('page_identifier')
        code_length = data.get('code_length', 32)
        expiration_hours = data.get('expiration_hours', 24)
        
        # Validate inputs
        if code_length < 16 or code_length > 128:
            return jsonify({
                'success': False,
                'error': 'code_length must be between 16 and 128'
            }), 400
        
        # Generate code
        secret_code = generate_secret_code(code_length)
        code_id = save_secret_code(secret_code, page_identifier, expiration_hours)
        
        if code_id is None:
            return jsonify({
                'success': False,
                'error': 'Failed to save code. Code may already exist.'
            }), 500
        
        expires_at = (datetime.now() + timedelta(hours=expiration_hours)).isoformat()
        
        return jsonify({
            'success': True,
            'code': secret_code,
            'code_id': code_id,
            'page_identifier': page_identifier,
            'expires_at': expires_at,
            'message': 'Secret code generated successfully'
        }), 201
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/validate-code', methods=['POST'])
def validate_code_endpoint():
    '''
    Validate if a code is valid and has not expired.
    
    Expected JSON payload:
    {
        "code": "secretcode123",
        "page_identifier": "dashboard"
    }
    
    Returns: Validation status
    '''
    try:
        data = request.get_json()
        
        if not data or 'code' not in data:
            return jsonify({
                'success': False,
                'error': 'code is required'
            }), 400
        
        code = data.get('code')
        page_identifier = data.get('page_identifier')
        
        result = verify_code_exists(code)
        
        if result is None:
            return jsonify({
                'success': False,
                'valid': False,
                'message': 'Code is invalid or expired'
            }), 200
        
        code_id, stored_page, expires_at = result
        
        if page_identifier and stored_page != page_identifier:
            return jsonify({
                'success': False,
                'valid': False,
                'message': 'Code does not match the specified page'
            }), 200
        
        return jsonify({
            'success': True,
            'valid': True,
            'code_id': code_id,
            'page_identifier': stored_page,
            'expires_at': expires_at,
            'message': 'Code is valid'
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/execute-code', methods=['POST'])
def execute_code_endpoint():
    '''
    Execute a secret code and record execution details.
    Tracks browser information and IP address.
    
    Expected JSON payload:
    {
        "code": "secretcode123",
        "page_identifier": "dashboard",
        "browser_info": "Mozilla/5.0..."
    }
    
    Returns: Execution status and result
    '''
    try:
        data = request.get_json()
        
        if not data or 'code' not in data:
            return jsonify({
                'success': False,
                'error': 'code is required'
            }), 400
        
        code = data.get('code')
        page_identifier = data.get('page_identifier')
        browser_info = data.get('browser_info', '')
        
        result = verify_code_exists(code)
        
        if result is None:
            return jsonify({
                'success': False,
                'executed': False,
                'message': 'Code is invalid or expired'
            }), 200
        
        code_id, stored_page, expires_at = result
        
        if page_identifier and stored_page != page_identifier:
            return jsonify({
                'success': False,
                'executed': False,
                'message': 'Code does not match the specified page'
            }), 200
        
        # Record execution
        record_execution(code_id, browser_info)
        
        return jsonify({
            'success': True,
            'executed': True,
            'code_id': code_id,
            'page_identifier': stored_page,
            'message': 'Code executed successfully',
            'execution_timestamp': datetime.now().isoformat()
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/code-status/<int:code_id>', methods=['GET'])
def get_code_status_endpoint(code_id):
    '''
    Retrieve the status and history of a specific code by its ID.
    
    Returns: Code metadata and execution history
    '''
    try:
        conn = sqlite3.connect(DB_FILE)
        cursor = conn.cursor()
        
        # Get code information
        cursor.execute('''
            SELECT code, page_identifier, created_at, expires_at, is_executed, execution_count
            FROM secret_codes WHERE id = ?
        ''', (code_id,))
        
        code_result = cursor.fetchone()
        
        if code_result is None:
            return jsonify({
                'success': False,
                'error': 'Code not found'
            }), 404
        
        code, page_id, created_at, expires_at, is_executed, exec_count = code_result
        
        # Get execution history
        cursor.execute('''
            SELECT executed_at, browser_info, ip_address FROM execution_history
            WHERE code_id = ? ORDER BY executed_at DESC
        ''', (code_id,))
        
        history = cursor.fetchall()
        conn.close()
        
        return jsonify({
            'success': True,
            'code_id': code_id,
            'code': code,
            'page_identifier': page_id,
            'created_at': created_at,
            'expires_at': expires_at,
            'is_executed': bool(is_executed),
            'execution_count': exec_count,
            'execution_history': [
                {
                    'executed_at': exec[0],
                    'browser_info': exec[1],
                    'ip_address': exec[2]
                } for exec in history
            ]
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    '''Health check endpoint for API status'''
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat()
    }), 200

if __name__ == '__main__':
    init_database()
    app.run(debug=False, host='0.0.0.0', port=5000)
Prompt: ساخت اپ تولید و جنراتور کدهای مخفی اجرایی بکند مناسب با هر صفحه فرانت و متصل کردن به ان وقابلیت اجرا در مرورگرها