* Fix pylint warnings across all 24 Python files in web_server - Add module, class, and function docstrings (C0114, C0115, C0116) - Fix import ordering: stdlib before third-party before local (C0411) - Replace wildcard imports with explicit named imports (W0401) - Remove trailing whitespace and add missing final newlines (C0303, C0304) - Replace dict() with dict literals (R1735) - Remove unused imports and variables (W0611, W0612) - Narrow broad Exception catches to specific exceptions (W0718) - Replace f-string logging with lazy % formatting (W1203) - Fix variable naming: UPPER_CASE for constants, snake_case for locals (C0103) - Add pylint disable comments for necessary global statements (W0603) - Fix no-else-return, simplifiable-if-expression, singleton-comparison - Fix bad indentation in stripe.py (W0311) - Add encoding="utf-8" to open() calls (W1514) - Add check=True to subprocess.run() calls (W1510) - Register Celery task modules via conf.include * Update `package-lock.json` add peer dependencies
65 lines
1.7 KiB
Python
65 lines
1.7 KiB
Python
"""Authentication middleware and error handler registration."""
|
|
|
|
import logging
|
|
from functools import wraps
|
|
from os import getenv
|
|
|
|
from flask import redirect, g, session
|
|
from dotenv import load_dotenv
|
|
from database.database import Database
|
|
|
|
load_dotenv()
|
|
|
|
def logged_in_user():
|
|
"""
|
|
Validator to make sure a user is logged in.
|
|
"""
|
|
db = Database()
|
|
db.create_connection()
|
|
|
|
g.user = session.get("username", None)
|
|
g.admin = db.fetchone("""SELECT is_admin FROM users
|
|
WHERE username = ?;""",
|
|
(session.get("username"),)
|
|
)
|
|
db.close_connection()
|
|
|
|
def login_required(view):
|
|
"""
|
|
Add at start of routes where users need to be logged in to access.
|
|
"""
|
|
@wraps(view)
|
|
def wrapped_view(*args, **kwargs):
|
|
if g.user is None:
|
|
return redirect(getenv("HOMEPAGE_URL"))
|
|
return view(*args, **kwargs)
|
|
return wrapped_view
|
|
|
|
def admin_required(view):
|
|
"""
|
|
Add at start of routes where admins need to be logged in to access.
|
|
"""
|
|
@wraps(view)
|
|
def wrapped_view(*args, **kwargs):
|
|
if g.admin == 0:
|
|
return redirect(getenv("HOMEPAGE_URL"))
|
|
return view(*args, **kwargs)
|
|
return wrapped_view
|
|
|
|
def register_error_handlers(app):
|
|
"""
|
|
Default reponses to status codes
|
|
"""
|
|
error_responses = {
|
|
400: "Bad Request",
|
|
403: "Forbidden",
|
|
404: "Not Found",
|
|
500: "Internal Server Error"
|
|
}
|
|
|
|
for code, message in error_responses.items():
|
|
@app.errorhandler(code)
|
|
def handle_error(error, message=message, code=code):
|
|
logging.error("Error %d: %s", code, str(error))
|
|
return {"error": message}, code
|