1+ import os
12import platform
3+ import uuid
24
35import dotenv
46from flask import Flask , jsonify , redirect , request
57from jose import jwt
68
7- from application .auth import get_or_create_user_id , handle_auth
9+ from application .auth import handle_auth
810
911from application .core .logging_config import setup_logging
1012
3840celery .config_from_object ("application.celeryconfig" )
3941api .init_app (app )
4042
43+ if settings .AUTH_TYPE in ("simple_jwt" , "session_jwt" ) and not settings .JWT_SECRET_KEY :
44+ key_file = ".jwt_secret_key"
45+ try :
46+ with open (key_file , "r" ) as f :
47+ settings .JWT_SECRET_KEY = f .read ().strip ()
48+ except FileNotFoundError :
49+ new_key = os .urandom (32 ).hex ()
50+ with open (key_file , "w" ) as f :
51+ f .write (new_key )
52+ settings .JWT_SECRET_KEY = new_key
53+ except Exception as e :
54+ raise RuntimeError (f"Failed to setup JWT_SECRET_KEY: { e } " )
55+
4156SIMPLE_JWT_TOKEN = None
4257if settings .AUTH_TYPE == "simple_jwt" :
43- user_id = get_or_create_user_id ()
44- payload = {"sub" : user_id }
58+ payload = {"sub" : "local" }
4559 SIMPLE_JWT_TOKEN = jwt .encode (payload , settings .JWT_SECRET_KEY , algorithm = "HS256" )
4660 print (f"Generated Simple JWT Token: { SIMPLE_JWT_TOKEN } " )
4761
@@ -54,13 +68,33 @@ def home():
5468 return "Welcome to DocsGPT Backend!"
5569
5670
71+ @app .route ("/api/config" )
72+ def get_config ():
73+ response = {
74+ "auth_type" : settings .AUTH_TYPE ,
75+ "requires_auth" : settings .AUTH_TYPE in ["simple_jwt" , "session_jwt" ],
76+ }
77+ return jsonify (response )
78+
79+
80+ @app .route ("/api/generate_token" )
81+ def generate_token ():
82+ if settings .AUTH_TYPE == "session_jwt" :
83+ new_user_id = str (uuid .uuid4 ())
84+ token = jwt .encode (
85+ {"sub" : new_user_id }, settings .JWT_SECRET_KEY , algorithm = "HS256"
86+ )
87+ return jsonify ({"token" : token })
88+ return jsonify ({"error" : "Token generation not allowed in current auth mode" }), 400
89+
90+
5791@app .before_request
5892def authenticate_request ():
5993 if request .method == "OPTIONS" :
6094 return "" , 200
6195
6296 decoded_token = handle_auth (request )
63- if "message" in decoded_token :
97+ if not decoded_token :
6498 request .decoded_token = None
6599 elif "error" in decoded_token :
66100 return jsonify (decoded_token ), 401
0 commit comments