From 2be2818c1bff7d67ba4c44d6224a3f5fbbb04d22 Mon Sep 17 00:00:00 2001
From: Carlos Brito <carlos.brito@cern.ch>
Date: Sat, 7 Dec 2024 13:30:10 -0300
Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=9A=91=20Fix=20usrbin=20info?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 simrad_server/__init__.py | 33 ++++++++++++++++++++++++++-------
 simrad_server/auth.py     |  7 ++++---
 simrad_server/index.py    | 23 ++++++++++++++++++++---
 3 files changed, 50 insertions(+), 13 deletions(-)

diff --git a/simrad_server/__init__.py b/simrad_server/__init__.py
index 8e19469..94414b6 100644
--- a/simrad_server/__init__.py
+++ b/simrad_server/__init__.py
@@ -1,6 +1,6 @@
 """.. moduleauthor:: Carlos Brito"""
 
-from flask import Flask
+from flask import Flask, request, jsonify
 from dotenv import load_dotenv
 from flask_cors import CORS
 import os
@@ -21,21 +21,32 @@ def create_app(test_config=None):
     if app.debug or app.testing:
         load_dotenv(".env.local")
 
+    CORS(
+        app,
+        # resources={
+        #     r"/*": {
+        #         "origins": ["http://127.0.0.1:5000", "http://localhost:8080", "https://simrad.cern.ch"],
+        #         "allow_credentials": True,
+        #         "methods": ["GET", "POST", "DELETE", "PUT", "OPTIONS"],
+        #     }
+        # },
+        supports_credentials=True,
+    )
+
     app.config['SESSION_COOKIE_SAMESITE'] = 'None'
     app.config['SESSION_COOKIE_SECURE'] = True
-    CORS(app)
 
     from .auth import oauth
     oauth.init_app(app)
 
-    if not app.testing:
-        from . import logger
-        logger.setup_logging(app)
+    # if not app.testing:
+    #     from . import logger
+    #     logger.setup_logging(app)
 
     from . import auth
     from . import index
 
-    app.register_blueprint(auth.bp)
+    app.register_blueprint(auth.bp, url_prefix="/auth")
     app.register_blueprint(index.bp)
 
     # DISCLAIMER: programmer responsability to make sure that all dash ids
@@ -59,5 +70,13 @@ def create_app(test_config=None):
     # app.route, while giving the blog blueprint a url_prefix, but for
     # the tutorial the blog will be the main index
     #app.add_url_rule("/", endpoint="index")
-
+    @app.before_request
+    def before_request():
+        headers = {
+            "Access-Control-Allow-Origin": "*",
+            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
+            "Access-Control-Allow-Headers": "Content-Type",
+        }
+        if request.method.lower() == "options":
+            return jsonify(headers), 200
     return app
diff --git a/simrad_server/auth.py b/simrad_server/auth.py
index fe7f952..14f6dbe 100644
--- a/simrad_server/auth.py
+++ b/simrad_server/auth.py
@@ -21,8 +21,9 @@ oauth.register(
     client_kwargs={"scope": "openid email profile"}
 )
 
-@bp.before_app_request
+@bp.before_request
 def require_login():
+    print("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
     if "user" not in session:
         if "_dash-" in request.path:
             return
@@ -39,9 +40,9 @@ def login():
 def auth():
     token = oauth.cern.authorize_access_token()
     session["user"] = token.get("userinfo")
-    return redirect("")
+    return redirect("/")
 
 @bp.route("/logout")
 def logout():
     session.pop("user", None)
-    return redirect("")
+    return redirect("/")
diff --git a/simrad_server/index.py b/simrad_server/index.py
index 6cadb14..2629a15 100644
--- a/simrad_server/index.py
+++ b/simrad_server/index.py
@@ -1,14 +1,28 @@
-from flask import Blueprint, g, make_response, session, request, jsonify, redirect, url_for
+from flask import Blueprint, g, make_response, session, request, jsonify, redirect, url_for, Response
 from .resources.scripts import plot, diff_plot, spectra, dict_spectra, dict_regular, plot_box
 from io import TextIOWrapper
 from .resources.scripts.plots.usrbin_plot import UsrbinPlot
 from .resources.scripts.utils.helpers.fluka_helpers import is_file_scoring, get_scoring_type
 from .resources.scripts.parsers.scoring_parsers.usrtrack_parser import UsrtrackParser
+from .resources.scripts.parsers.scoring_parsers.usrbin_parser import UsrbinParser
 import os
 from werkzeug.utils import secure_filename
 from urllib.request import unquote
+import numpy as np
+
 bp = Blueprint("index", __name__)
 
+def require_login():
+    """Shared authentication logic."""
+    if "user" not in session:
+        print("User not in session")
+        return redirect(url_for("auth.login", _scheme="https"))
+
+@bp.before_request
+def authenticate():
+    """Apply authentication to the index blueprint."""
+    require_login()
+
 @bp.route("/user")
 def get_user():
     response = make_response(session["user"], 200)
@@ -246,7 +260,7 @@ def usrbin_info():
     file = request.files['file']
     file_name = secure_filename(file.filename)
     backend_dir = os.getenv("CACHE_DIR", "temporary_backend/")
-    file_path = os.path.join(backend_dir, filename)
+    file_path = os.path.join(backend_dir, file_name)
     file.save(file_path)
     scoring_type = get_scoring_type(file_path)
     if (scoring_type != 'usrbin'):
@@ -255,6 +269,9 @@ def usrbin_info():
         return jsonify({'error': error_msg}), 400
     else:
         bins = UsrbinParser.get_bins(file_path)
+        for bin_data in bins:
+            if isinstance(bin_data['data'], np.ndarray):
+                bin_data['data'] = bin_data['data'].tolist()  # Convert ndarray to list
 
         return jsonify(*bins), 200
 
@@ -269,7 +286,7 @@ def usrtrack_info():
     file = request.files['file']
     file_name = secure_filename(file.filename)
     backend_dir = os.getenv("CACHE_DIR", "temporary_backend/")
-    file_path = os.path.join(backend_dir, filename)
+    file_path = os.path.join(backend_dir, file_name)
     file.save(file_path)
     scoring_type = get_scoring_type(file_path)
     if (scoring_type != 'usrtrack'):
-- 
GitLab


From 6feea2f6bc5b5fce38f8ffb553067b1c1ceb038b Mon Sep 17 00:00:00 2001
From: Carlos Brito <carlos.brito@cern.ch>
Date: Sat, 7 Dec 2024 13:34:41 -0300
Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=9A=91=20Fix=20usrbin=20info?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 simrad_server/index.py | 1 -
 1 file changed, 1 deletion(-)

diff --git a/simrad_server/index.py b/simrad_server/index.py
index 2629a15..18ac2f6 100644
--- a/simrad_server/index.py
+++ b/simrad_server/index.py
@@ -15,7 +15,6 @@ bp = Blueprint("index", __name__)
 def require_login():
     """Shared authentication logic."""
     if "user" not in session:
-        print("User not in session")
         return redirect(url_for("auth.login", _scheme="https"))
 
 @bp.before_request
-- 
GitLab