Files
eveAI/common/utils/middleware.py
Josako a237db339a - Improved CSRF handling
- Wordpress plugin for Evie Chat
2024-08-13 14:31:29 +02:00

37 lines
1.0 KiB
Python

"""Middleware for the API
for handling tenant requests
"""
from flask_security import current_user
from flask import session, current_app, redirect
from common.utils.nginx_utils import prefixed_url_for
from .database import Database
def mw_before_request():
"""Before request
switch tenant schema
"""
if 'tenant' not in session:
current_app.logger.warning('No tenant defined in session')
return redirect(prefixed_url_for('security_bp.login'))
tenant_id = session['tenant']['id']
if not tenant_id:
raise Exception('Cannot switch schema for tenant: no tenant defined in session')
for role in current_user.roles:
current_app.logger.debug(f'In middleware: User {current_user.email} has role {role.name}')
# user = User.query.get(current_user.id)
if current_user.has_role('Super User') or current_user.tenant_id == tenant_id:
Database(tenant_id).switch_schema()
else:
raise Exception(f'Cannot switch schema for tenant {tenant_id}: user {current_user.email} does not have access')