#!/usr/bin/env python3
"""
Legacy Web Service - Vulnerable Example
Demonstrates weak crypto, poor practices, outdated dependencies
"""

from flask import Flask, jsonify, request
import ssl
import logging

# Weak SSL configuration
app = Flask(__name__)
app.secret_key = 'hardcoded_secret_key_123'  # WEAK!

# Configure logging without sanitization
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)


@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({'status': 'healthy'}), 200


@app.route('/api/users', methods=['GET'])
def get_users():
    """Get users - vulnerable to injection"""
    user_id = request.args.get('id', '')
    # VULNERABLE: No input validation or parameterization
    query = f"SELECT * FROM users WHERE id = {user_id}"
    
    return jsonify({
        'users': [],
        'message': 'User data retrieved'
    }), 200


@app.route('/api/login', methods=['POST'])
def login():
    """Login endpoint with weak password hashing"""
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    # VULNERABLE: Plain text password storage (implied by legacy code)
    # VULNERABLE: No rate limiting
    
    return jsonify({
        'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U',
        'username': username
    }), 200


@app.route('/api/config', methods=['GET'])
def get_config():
    """Return configuration - VULNERABLE: exposes sensitive info"""
    return jsonify({
        'database': 'postgresql://demo_user:demo_password_123@demo-postgres:5432/demo_db',
        'api_key': 'sk_live_abc123def456',
        'redis_url': 'redis://demo-redis:6379',
        'encryption_key': 'weak_encryption_key_for_demo'
    }), 200


@app.route('/api/data', methods=['POST'])
def post_data():
    """Receive and store data - no validation"""
    data = request.get_json()
    
    # VULNERABLE: No input validation
    # VULNERABLE: No CSRF protection
    # VULNERABLE: No authentication
    
    logger.debug(f"Received data: {data}")  # DANGEROUS: Logs sensitive data
    
    return jsonify({'status': 'saved'}), 201


@app.route('/api/files/<filename>', methods=['GET'])
def get_file(filename):
    """Get file - vulnerable to path traversal"""
    # VULNERABLE: No path validation, allows directory traversal
    with open(f'/app/files/{filename}', 'r') as f:
        content = f.read()
    
    return jsonify({'content': content}), 200


if __name__ == '__main__':
    # VULNERABLE: Weak SSL/TLS configuration
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)  # Outdated TLS version!
    context.load_cert_chain(
        certfile='/app/cert.pem',
        keyfile='/app/key.pem'
    )
    
    # VULNERABLE: Debug mode enabled in production-like setup
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=True,  # DANGEROUS!
        ssl_context=context
    )
