1

We have our own login decorator and we want to disable the default @login_required so anyone who will import and use the original decorator will get an exception.

How can we money-patch / disable this function?

Edit: As I read the comments I understand that this is the wrong approach. we've added 2fa authentication and with it wrote this decorator to replace @login_required:

def is_user_2fa(user):
    for company in user.companies:
        if company.two_factor_auth:
            return True
    return False


def tfa_authenticated(user):
    return user.is_verified() or (user.is_authenticated() and not is_user_2fa(user))


def login_2fa_required(view=None, redirect_field_name='next', login_url=None):
    if login_url is None:
        login_url = settings.OTP_LOGIN_URL

    def test(user):
        return tfa_authenticated(user)
    decorator = user_passes_test(test, login_url=login_url, redirect_field_name=redirect_field_name)
    return decorator if (view is None) else decorator(view)

What's right way to keep @login_required while enforcing 2fa when it applies?

Thank you

kambi
  • 3,291
  • 10
  • 37
  • 58
  • You can monkey-patch it, but views that have already been decorated, will still require login. – Willem Van Onsem Aug 23 '18 at 07:56
  • 2
    I wonder however if you are not solving the "wrong" problem. `@login_required` only checks if `user.is_authenticated()`, etc. So instead of getting rid of the `@login_required`, you can define a different `is_autheticated` on your custom user model. – Willem Van Onsem Aug 23 '18 at 07:58
  • 5
    Are you sure you really need this? You can customize a lot of things about the login behaviour without monkey-patching: custom user model with custom `is_authenticated`, custom authentication backends, custom login_url setting, etc. – user2390182 Aug 23 '18 at 07:59
  • 5
    It sound a bit like you did not properly include your requirements into Django's authentication system. If you would have done that `@login_required` would still work as before. I case you just implemented a decorator: sorry, but you did it wrong. – Klaus D. Aug 23 '18 at 08:04
  • The Django documentation has a topic on this subject: https://docs.djangoproject.com/en/2.1/topics/auth/customizing/ – Willem Van Onsem Aug 23 '18 at 08:09
  • If you've written your own decorator because the default one does not work, that implies you have also written your own authentication system which you **absolutely must not do**. – Daniel Roseman Aug 23 '18 at 08:20
  • Thanks guys I've edited the question maybe you'll be able to further point me to the right direction. – kambi Aug 23 '18 at 08:44
  • Did you checked this https://stackoverflow.com/questions/7667567/can-i-patch-a-python-decorator-before-it-wraps-a-function ? – Umair Mohammad Aug 23 '18 at 08:46

0 Answers0