File size: 4,112 Bytes
12f0507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""
MedMembers OFT 2026 - Secure Question Bank Web Application
"""

import os
import json
import mimetypes
from flask import Flask, send_from_directory, send_file, request, jsonify, g
from config import Config
from models.database import init_db, close_db, get_db
from auth.routes import auth_bp
from auth.middleware import require_auth
from api.questions import questions_bp
from api.admin import admin_bp
from api.video_proxy import video_bp
from api.media import media_bp
from security.headers import apply_security_headers
from sockets.heartbeat import socketio, start_cleanup_task


def create_app():
    app = Flask(__name__, static_folder='static', static_url_path='/static')
    app.config['SECRET_KEY'] = Config.SECRET_KEY

    # Register blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(questions_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(video_bp)
    app.register_blueprint(media_bp)

    # Apply security headers
    apply_security_headers(app)

    # Initialize database
    with app.app_context():
        init_db()

    # Close DB connection after each request
    @app.teardown_appcontext
    def shutdown_session(exception=None):
        close_db()

    # Serve media images from secure_media folder
    MEDIA_DIR = Config.MEDIA_DIR

    @app.route('/api/images/<path:filepath>')
    @require_auth
    def serve_image(filepath):
        """Serve question images securely (requires auth)."""
        safe_path = os.path.normpath(filepath)
        if '..' in safe_path or safe_path.startswith(('/', '\\')):
            return jsonify({'error': 'Invalid path'}), 400

        # Try media dir
        full_path = os.path.join(MEDIA_DIR, safe_path)
        if not os.path.exists(full_path):
            # Try data/images
            full_path = os.path.join(Config.DATA_DIR, 'images', safe_path)

        if not os.path.exists(full_path):
            return jsonify({'error': 'Image not found'}), 404

        mime_type, _ = mimetypes.guess_type(full_path)
        if not mime_type or not (mime_type.startswith('image/') or mime_type.startswith('video/')):
            return jsonify({'error': 'Not a media file'}), 400

        response = send_file(full_path, mimetype=mime_type)
        response.headers['Cache-Control'] = 'private, max-age=3600'
        return response

    # Serve media (video/image) from secure_media
    @app.route('/api/media-file/<path:filepath>')
    @require_auth
    def serve_media_file(filepath):
        """Serve media files from secure_media folder."""
        safe_path = os.path.normpath(filepath)
        if '..' in safe_path or safe_path.startswith(('/', '\\')):
            return jsonify({'error': 'Invalid path'}), 400

        full_path = os.path.join(MEDIA_DIR, safe_path)
        if not os.path.exists(full_path):
            return jsonify({'error': 'File not found'}), 404

        mime_type, _ = mimetypes.guess_type(full_path)
        if not mime_type:
            mime_type = 'application/octet-stream'

        response = send_file(full_path, mimetype=mime_type)
        response.headers['Cache-Control'] = 'private, max-age=3600'
        response.headers['Content-Disposition'] = 'inline'
        return response

    # SPA catch-all: serve index.html for all non-API routes
    @app.route('/')
    @app.route('/<path:path>')
    def serve_spa(path=''):
        if path.startswith('api/') or path.startswith('static/'):
            return app.send_static_file(path) if path.startswith('static/') else ('', 404)
        return send_from_directory(app.static_folder, 'index.html')

    # Initialize SocketIO
    socketio.init_app(app)

    # Start background cleanup task
    start_cleanup_task(app)

    return app


app = create_app()

if __name__ == '__main__':
    print("\n" + "=" * 60)
    print("MedMembers OFT 2026 - Servidor Web")
    print("=" * 60)
    print(f"Database: {Config.DB_PATH}")
    print(f"Media: {Config.MEDIA_DIR}")
    print(f"Admin: {Config.ADMIN_EMAIL}")
    print("=" * 60 + "\n")

    socketio.run(app, host='0.0.0.0', port=5000, debug=True, allow_unsafe_werkzeug=True)