diff --git a/trench/decorators.py b/trench/decorators.py new file mode 100644 index 00000000..92781f6d --- /dev/null +++ b/trench/decorators.py @@ -0,0 +1,23 @@ +from django.contrib.auth import REDIRECT_FIELD_NAME +from django.contrib.auth.decorators import user_passes_test + + +def mfa_login_required( + function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None +): + """ + Decorator for views that checks that the user is logged in, redirecting + to the log-in page if necessary. + """ + + def is_user_authenticated(user): + return user.is_authenticated + + actual_decorator = user_passes_test( + is_user_authenticated, + login_url=login_url, + redirect_field_name=redirect_field_name, + ) + if function: + return actual_decorator(function) + return actual_decorator diff --git a/trench/views/base.py b/trench/views/base.py index c013cc5a..07d93c1c 100644 --- a/trench/views/base.py +++ b/trench/views/base.py @@ -1,5 +1,6 @@ from django.contrib.auth.models import User from django.db.models import QuerySet +from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy as _ from abc import ABC, abstractmethod @@ -24,6 +25,7 @@ regenerate_backup_codes_for_mfa_method_command, ) from trench.command.set_primary_mfa_method import set_primary_mfa_method_command +from trench.decorators import mfa_login_required from trench.exceptions import MFAMethodDoesNotExistError, MFAValidationError from trench.query.get_mfa_config_by_name import get_mfa_config_by_name_query from trench.responses import ErrorResponse @@ -225,6 +227,10 @@ def post(request: Request) -> Response: except MFAValidationError as cause: return ErrorResponse(error=cause) + # @method_decorator(mfa_login_required) + # def dispatch(self, *args, **kwargs): + # return super().dispatch(*args, **kwargs) + class MFAPrimaryMethodChangeView(APIView): permission_classes = (IsAuthenticated,)