diff --git a/biscuit/core/util/core_helpers.py b/biscuit/core/util/core_helpers.py index 23efbf02b06f569b9ef64c2a9443a033b7a8ad35..d6757d9c38e5668157a1bcfd002e5164b77303c6 100644 --- a/biscuit/core/util/core_helpers.py +++ b/biscuit/core/util/core_helpers.py @@ -1,6 +1,10 @@ from importlib import import_module import pkgutil from typing import Optional, Sequence +from warnings import warn + +from django.apps import apps +from django.conf import settings from django_global_request.middleware import get_request @@ -34,14 +38,28 @@ def get_current_school() -> Optional: request = get_request() if request: - if not hasattr(request, 'user'): - return None - if not hasattr(request.user, 'person'): - return None + # We are inside a web request, thus called from a public interface - if request.user.person: + if hasattr(request, 'user') and hasattr(request.user, 'person'): + # Use the same school as that of the logged-in user return request.user.person.school else: + # Set no school so no data is ever returned + # during an unauthenticated request return None else: - return None + # We are called from outside a request (probably shell), + # thus called from a private interface + + School = apps.get_model('core.School') + + if 'DEFAULT_SCHOOL' in settings: + # Use school defined in settings + return School.objects.get(pk=settings.DEFAULT_SCHOOL) + else: + # Use first school + warn('No school set, using first known school.', RuntimeWarning) + return School.objects.first() + + # Raise an exception because not finding a school wreaks havoc + raise RuntimeError('No school set or found. Check your database.')