2

I am currently using the package 'django-two-factor-authentication' in my Django project and I see the management commands here (https://django-two-factor-auth.readthedocs.io/en/1.14.0/management-commands.html)

My client would like to have a specific message for users who have not enabled two factor authentication. How would I call this from a view to check their status?

I tried this already:

from django.core.management import call_command
authed = call_command('two_factor_status fake_email@gmail.com')
print('authed response')
print(authed)

but I get an error message saying that this is an unknown command. If I leave the email out the page doesn't crash and I don't get an error but it prints out "None".

***Update With this specific package you can check if the user has enabled two factor authentication with

request.user.is_verified

I would still like to know if there is a way to call management commands from a view when they are from a third party package though.

Jake Mulhern
  • 660
  • 5
  • 13
  • I think you should pass the package name to call_command( 'package_name', 'two_factor_status fake_email@gmail.com') and then print the result from stdout as call_command return result on stdout. – Umar Hayat Jul 14 '22 at 17:39
  • I just get an error saying that 'two_factor' is an unknown command when I try this. – Jake Mulhern Jul 14 '22 at 19:40
  • Please check if you can call the command from the command line – JanMalte Jul 14 '22 at 20:00
  • I have checked and it does work with ``` python manage.py two_factor_status fake_email@gmail.com ``` – Jake Mulhern Jul 14 '22 at 20:02

1 Answers1

0

You have to split the command and arguments. Please notice, that you will only get the value the handle() method of the command returns, if any, and not the output which will be printed if you execute the command.

from django.core.management import call_command
call_command('two_factor_status', 'fake_email@gmail.com')

I would recommend not to call the command but use the logic directly in the view. This reduces the overhead and allows more granular handling of the response.

from django.contrib.auth import get_user_model
from two_factor.utils import default_device

def your_view(request):
    # ... your code
    user = User.objects.get_by_natural_key(username)
    if default_device(user):
        # 2FA enabled
    else:
        # 2FA not enabled
JanMalte
  • 934
  • 6
  • 17