"""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') # 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')