Working log in/route guard

This commit is contained in:
2025-09-04 08:05:01 -04:00
parent d250e136c3
commit 20f9a4485e
9 changed files with 199 additions and 355 deletions

View File

@@ -11,7 +11,7 @@ from sqlalchemy.orm import sessionmaker
from werkzeug.routing import BaseConverter
from flask_mail import Mail
from config import load_config
import re
ApplicationConfig = load_config()
@@ -70,29 +70,28 @@ login_manager.anonymous_user = "Guest"
@login_manager.request_loader
def load_user_from_request(request):
from app.classes.auth import Auth_User
# first, try to log in using the api_key url arg
api_key = request.args.get('api_key')
if api_key:
user = db.session\
.query(Auth_User)\
.filter_by(api_key=api_key)\
.first()
if user:
return user
# next, try to log in using Basic Auth
api_key_auth = request.headers.get('Authorization')
if api_key_auth:
api_key = api_key_auth.replace('bearer ', '', 1)
if api_key.startswith('"') and api_key.endswith('"'):
api_key = api_key[1:-1]
user = db.session\
.query(Auth_User)\
.filter_by(api_key=api_key)\
.first()
if user:
return user
return None
# Check for Authorization header first, as it's the standard
auth_header = request.headers.get('Authorization')
if auth_header:
# --- THIS IS THE FIX ---
# Use a case-insensitive regular expression to strip "bearer "
api_key = re.sub(r'^bearer\s+', '', auth_header, flags=re.IGNORECASE).strip('"')
if api_key:
user = db.session.query(Auth_User).filter_by(api_key=api_key).first()
if user:
return user
# As a fallback, check for api_key in URL args (less secure, but keeps existing logic)
api_key_arg = request.args.get('api_key')
if api_key_arg:
user = db.session.query(Auth_User).filter_by(api_key=api_key_arg).first()
if user:
return user
# If no valid key is found in header or args, return None
return None
# api_main = {
# "origins": [ApplicationConfig.ORIGIN_URL],