在我的测试用例中,如何使用django-two-factor-auth完全验证测试用户以访问OTPRequiredMixin视图?

uemypmqf  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(143)

我正在尝试为我的类视图编写测试用例,这些类视图在django-two-factor-auth OTPRequiredMixin之后是安全的。我不确定如何编写setUp函数来通过OTP对用户进行完全身份验证。我尝试过self.client.force_login(),但当我尝试在测试函数中浏览该URL时,我登陆到了“Permission Denied”页面,提示为用户启用双因素身份验证。而不是预期的URL。

权限被拒绝

出于安全原因,您请求得页强制用户使用双重身份验证进行验证.您需要启用这些安全功能才能访问此页.
没有为你的帐户启用双重身份验证。启用双重身份验证以增强帐户安全性。
下面是其中一个类视图的示例:

class ProjectCreateView(OTPRequiredMixin, CreateView):
    model = Project
    template_name = 'project_create.html'
    fields = ['name', 'description']

下面是我的设置和测试示例:

class ProjectTestCase(TestCase):
    def setUp(self):
        self.user = get_user_model().objects.create(
            username='jsmith', first_name='John', last_name='Smith', email='johnsmith@test.com', password='secure'
        )
        [...]
        self.client.force_login(self.user)

    def test_project_create(self):
        response = self.client.post(
            '/project/create/', {'name': 'Test Project', 'description': 'A basic test project'}
        )
        self.assertEqual(response.status_code, 200)
jljoyd4f

jljoyd4f1#

我花了一段时间查看django-two-factor-auth源代码来解决这个问题。
https://github.com/jazzband/django-two-factor-auth/blob/d7abfd74363ba27ceb5ea3c61a8784ebffb46c6c/tests/test_views_login.py#L21
我在“test_with_backup_token”中找到了一个似乎对我有效的示例,它基本上创建了一个备份令牌,然后使用它来完成2FA身份验证。

from django_otp.util import random_hex


# Create your tests here.
class WonderfulTestCase(TestCase):

    def setUp(self):

       # username, email, password
       self.cool_user = User.objects.create_user("bob_is_cool", 
                                                 "bob@hotmail.com", 
                                                 "super_cool_password")

        # create OTP stuff including a backup token
        self.cool_user.totpdevice_set.create(name='default', key=random_hex())
        device = self.cool_user.staticdevice_set.create(name='backup')
        device.token_set.create(token='abcdef123')

        # first auth step
        response = self.client.post(reverse('two_factor:login'), {'auth-username': "bob_is_cool", 'auth-password': "super_cool_password", 'login_view-current_step': 'auth'})

        # go to backup step
        response = self.client.post(reverse('two_factor:login'), {'wizard_goto_step': 'backup'})

        # Valid token should be accepted.
        response = self.client.post(reverse('two_factor:login'), {'backup-otp_token': 'abcdef123', 'login_view-current_step': 'backup'})

相关问题