Spaces:
Runtime error

File size: 8,354 Bytes
59f2028
 
 
 
 
 
 
 
 
 
 
 
 
 
9ff1836
 
 
59f2028
9ff1836
6d37fa5
59f2028
 
 
115cc7b
7747820
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59f2028
 
115cc7b
59f2028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115cc7b
59f2028
 
 
115cc7b
 
59f2028
 
 
115cc7b
59f2028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115cc7b
 
 
59f2028
115cc7b
59f2028
 
115cc7b
59f2028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ff1836
6d37fa5
59f2028
 
 
 
0815850
 
59f2028
 
 
 
6d37fa5
59f2028
 
 
 
 
 
 
 
6d37fa5
 
59f2028
 
115cc7b
59f2028
 
115cc7b
6d37fa5
 
59f2028
 
 
 
 
9ff1836
59f2028
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""
MJ Learn Backend - Main Flask Application

A clean, professional Flask application with modular authentication.

Main Features:
- JWT-based authentication system
- Role-based access control (admin/user)
- Secure token management with blacklisting
- CORS configuration for cross-origin requests
- Modular blueprint architecture
- Environment-based configuration
"""

import os
from dotenv import load_dotenv
import logging
from flask import Flask, request
from flask_cors import CORS

# Load environment variables first
BASEDIR = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(BASEDIR, ".env"))

print("✅ STORAGE CHECK (startup)")
print("BASEDIR:", BASEDIR)
print("CWD:", os.getcwd())

# Common paths to verify
paths_to_check = [
    "/data",
    "/data/auth_db",
    "/data/chroma",
    os.path.join(BASEDIR, "data"),
    os.path.abspath(os.path.join(BASEDIR, "data")),
    "/home/user/app/data",
]

for p in paths_to_check:
    exists = os.path.exists(p)
    writable = os.access(p, os.W_OK) if exists else False
    print(f"Path: {p}")
    print(f"  - exists: {exists}")
    print(f"  - writable: {writable}")
    if exists:
        try:
            items = os.listdir(p)
            print(f"  - list (first 30): {items[:30]}")
        except Exception as e:
            print(f"  - list error: {e}")

# Show auth env values (for confirmation)
print("ENV VALUES:")
print("  AUTH_DB_DIR  =", os.getenv("AUTH_DB_DIR"))
print("  CHROMA_ROOT  =", os.getenv("CHROMA_ROOT"))
print("  USE_JSON_DB  =", os.getenv("USE_JSON_DB"))
print("  ENV          =", os.getenv("ENV"))

# --- Build local ChromaDB at startup (expects build_chroma_db.py in same folder) ---
_CHROMA_SCRIPT_PATH = os.path.join(BASEDIR, "build_chroma_db.py")

if os.path.exists(_CHROMA_SCRIPT_PATH):
    try:
        import importlib.util
        import traceback

        spec = importlib.util.spec_from_file_location("build_chroma_db_local", _CHROMA_SCRIPT_PATH)
        build_chroma_mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(build_chroma_mod)

        if hasattr(build_chroma_mod, "build_chroma"):
            # Run the builder to create Chroma DB in the local assets folder
            build_chroma_mod.build_chroma()
            print("✅ build_chroma_db.build_chroma() executed successfully.")
        else:
            print("!! build_chroma_db.py found but no `build_chroma()` function present.")
    except Exception as e:
        print(f"!! Failed to run build_chroma_db.py: {e}")
        traceback.print_exc()
else:
    print("!! build_chroma_db.py not found in the application folder — skipping Chroma build.")
# --- End ChromaDB build block ---

# Import authentication module
from auth import auth_bp
from auth.database import ensure_database_initialized


def create_app():
    """Application factory pattern for Flask app creation"""
    app = Flask(__name__)
    
    # Security configuration
    app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
    if not app.config['SECRET_KEY']:
        raise RuntimeError("SECRET_KEY must be set in environment variables!")
    
    # Environment configuration
    IS_PROD = os.getenv("ENV", "dev").lower() == "prod"
    
    # CORS configuration
    _default_origins = "http://localhost:4200,http://127.0.0.1:4200"
    _origins = os.getenv("ALLOWED_ORIGINS", _default_origins)
    ALLOWED_ORIGINS = [o.strip() for o in _origins.split(",") if o.strip()]
    
    CORS(
        app,
        resources={r"/*": {"origins": ALLOWED_ORIGINS}},
        supports_credentials=True,
        allow_headers=["Content-Type", "Authorization", "X-Requested-With", "X-User"],
        expose_headers=["Set-Cookie"],
        methods=["GET", "POST", "OPTIONS"]
    )
    
    # API configuration for blueprints
    app.config["COHERE_API_KEY"] = os.getenv("COHERE_API_KEY", "")
    
    # CORS handlers
    @app.after_request
    def add_cors_headers(resp):
        origin = request.headers.get("Origin")
        if origin and origin in ALLOWED_ORIGINS:
            resp.headers["Access-Control-Allow-Origin"] = origin
            resp.headers["Vary"] = "Origin"
            resp.headers["Access-Control-Allow-Credentials"] = "true"
            resp.headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization, X-Requested-With, X-User"
            resp.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
        return resp
    
    @app.before_request
    def handle_options_early():
        if request.method == "OPTIONS":
            resp = app.make_default_options_response()
            origin = request.headers.get("Origin")
            if origin and origin in ALLOWED_ORIGINS:
                resp.headers["Access-Control-Allow-Origin"] = origin
                resp.headers["Access-Control-Allow-Credentials"] = "true"
            # Mirror browser's requested headers/methods
            req_headers = request.headers.get("Access-Control-Request-Headers", "Content-Type, Authorization, X-Requested-With, X-User")
            req_method = request.headers.get("Access-Control-Request-Method", "POST")
            resp.headers["Access-Control-Allow-Headers"] = req_headers
            resp.headers["Access-Control-Allow-Methods"] = req_method
            return resp
    
    # Initialize database before first request (Flask 3.x compatible)
    @app.before_request
    def maybe_initialize_database():
        if not hasattr(app, '_db_initialized'):
            try:
                ensure_database_initialized()
                app._db_initialized = True
            except Exception as e:
                app.logger.exception("Database initialization failed: %s", e)
    
    # Health check endpoint
    @app.route("/")
    def health():
        return {"status": "ok", "service": "MJ Learn Backend"}, 200
    
    # Register authentication blueprint
    app.register_blueprint(auth_bp, url_prefix="/auth")
    
    # Register other feature blueprints
    register_feature_blueprints(app)
    
    return app


def register_feature_blueprints(app):
    """Register feature blueprints with error handling"""
    blueprints = [       
        ("ragg.app", "rag_bp", "/rag"),
        ("pronunciation", "pronunciation_bp", "/pronunciation"),
        ("staticchat", "staticchat_bp", "/staticchat"),
        ("ragg.ingest_trigger", "ingest_trigger_bp", "/rag"),
    ]
    
    for module_name, blueprint_name, url_prefix in blueprints:
        try:
            module = __import__(module_name, fromlist=[blueprint_name])
            blueprint = getattr(module, blueprint_name)
            app.register_blueprint(blueprint, url_prefix=url_prefix)
            print(f"? Registered {blueprint_name}")
        except ImportError as e:
            print(f"?? Could not import {blueprint_name}: {e}")
        except AttributeError as e:
            print(f"?? Blueprint {blueprint_name} not found in {module_name}: {e}")


# Create Flask app instance
app = create_app()

# Configure logging
logging.basicConfig(level=logging.INFO)


if __name__ == '__main__':
    print("?? Starting MJ Learn Backend...")
    print(f"? SECRET_KEY loaded: {bool(app.config.get('SECRET_KEY'))}")
    print(f"? Environment: {os.getenv('ENV', 'development')}")
    print("=" * 60)
    
    port = int(os.getenv("PORT", "5000"))
    print(f"?? Server starting on http://localhost:{port}")
    print("?? Available endpoints:")
    print("   GET  /                    - Health check")
    print("   ?? Authentication:")
    print("   POST /auth/signup         - User registration")
    print("   POST /auth/login          - User login")
    print("   POST /auth/refresh        - Token refresh")
    print("   POST /auth/logout         - User logout")
    print("   GET  /auth/dashboard      - Protected endpoint")
    print("   GET  /auth/check-auth     - Auth status check")
    print("   GET  /auth/db/diag        - Database diagnostics (ADMIN)")
    print("   ?? Admin Management:")
    print("   GET  /auth/admin/users          - List all users (ADMIN)")
    print("   POST /auth/admin/promote-user   - Promote user to admin (ADMIN)")  
    print("   POST /auth/admin/create-first-admin - Create first admin")
    print("=" * 60)
    
    try:
        app.run(host="0.0.0.0", port=port, debug=True)
    except Exception as e:
        print(f"? Failed to start server: {e}")
        raise