Пример #1
0
    def setUp(self):
        """
        Create a course, and enroll a student user and staff user.
        """
        super(RosterDataTest, self).setUp()
        self.course = CourseFactory.create()
        self.course_key = self.course.id

        self.student = UserFactory.build(
            username=self.STUDENT_USERNAME,
            email=self.STUDENT_EMAIL,
            password=self.STUDENT_PASSWORD,
        )
        self.student.save()
        UserProfileFactory.create(user=self.student, name=self.STUDENT_NAME)

        self.staff = UserFactory.build(
            username=self.STAFF_USERNAME,
            email=self.STAFF_EMAIL,
            password=self.STAFF_PASSWORD,
        )
        self.staff.save()
        UserProfileFactory.create(user=self.staff, name=self.STAFF_NAME)

        CourseEnrollment.enroll(self.student, self.course_key, mode="honor")
        CourseEnrollment.enroll(self.staff, self.course_key, mode="honor")
        CourseStaffRole(self.course_key).add_users(self.staff)
Пример #2
0
    def test_user_me_with_logged_in_user(self):
        """
        If user is authenticated through Django session, view should return
        a JSON object containing the username and a JWT access token
        """
        user = UserFactory.create(
            username="******",
            email="*****@*****.**",
        )
        UserProfileFactory.build(user=user, name="Arthur Fonzarelli")
        self.client.force_authenticate(user=user)

        response = self.client.get(self.url)
        token = jwt.decode(
            response.data["access_token"],
            "ThisIsAnExampleKeyForDevPurposeOnly",
            options={
                "require":
                ["email", "exp", "iat", "jti", "token_type", "username"]
            },
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["username"], "fonzie")
        self.assertEqual(token["username"], "fonzie")
        self.assertEqual(token["full_name"], "Arthur Fonzarelli")
        self.assertEqual(token["email"], "*****@*****.**")
        self.assertEqual(token["token_type"], "access")
        self.assertIsInstance(token["exp"], int)
        self.assertIsInstance(token["iat"], int)
class TestJwtBuilder(mixins.AccessTokenMixin, TestCase):
    """
    Test class for JwtBuilder.
    """

    expires_in = 10
    shard = 2

    def setUp(self):
        super(TestJwtBuilder, self).setUp()

        self.user = UserFactory()
        self.profile = UserProfileFactory(user=self.user)

    @ddt.data(
        [],
        ['email'],
        ['profile'],
        ['email', 'profile'],
    )
    def test_jwt_construction(self, scopes):
        """
        Verify that a valid JWT is built, including claims for the requested scopes.
        """
        token = JwtBuilder(self.user).build_token(scopes, self.expires_in)
        self.assert_valid_jwt_access_token(token, self.user, scopes)

    def test_user_profile_missing(self):
        """
        Verify that token construction succeeds if the UserProfile is missing.
        """
        self.profile.delete()

        scopes = ['profile']
        token = JwtBuilder(self.user).build_token(scopes, self.expires_in)
        self.assert_valid_jwt_access_token(token, self.user, scopes)

    def test_override_secret_and_audience_and_issuer(self):
        """
        Verify that the signing key, audience, and issuer can be overridden.
        """
        secret = 'avoid-this'
        audience = 'avoid-this-too'
        issuer = 'avoid-this-too'
        scopes = []

        token = JwtBuilder(
            self.user,
            secret=secret,
            issuer=issuer,
        ).build_token(
            scopes,
            self.expires_in,
            aud=audience,
        )

        jwt.decode(token, secret, audience=audience, issuer=issuer)
Пример #4
0
    def setUp(self):
        self.factory = RequestFactory()
        self.course_id = 'Test/Course/Test'
        self.mode, created = self.create_mode('pay_with_coupon', 'Pay with coupon', min_price=100, currency='usd')
        self.coupon_name = 'test-coupon'
        self.coupon, created = self.create_coupon(self.coupon_name, 25)

        self.user = User.objects.create_user('test', '*****@*****.**', 'test')
        UserProfileFactory.create(user=self.user, name='Gary Test')
        self.client.login(username='******', password='******')

        class mock_customer(object):
            id = 'customer_test_id_32'
        self.mock_customer = mock_customer
Пример #5
0
class TestDeprecatedJwtBuilder(mixins.AccessTokenMixin, TestCase):
    """
    Test class for the deprecated JwtBuilder class.
    """

    expires_in = 10
    shard = 2

    def setUp(self):
        super(TestDeprecatedJwtBuilder, self).setUp()

        self.user = UserFactory()
        self.profile = UserProfileFactory(user=self.user)
        self.scopes = ['email', 'profile']

    def test_jwt_construction(self):
        """
        Verify that a valid JWT is built, including claims for the requested scopes.
        """
        token = JwtBuilder(self.user).build_token(expires_in=self.expires_in)
        self.assert_valid_jwt_access_token(token, self.user, self.scopes)

    def test_user_profile_missing(self):
        """
        Verify that token construction succeeds if the UserProfile is missing.
        """
        self.profile.delete()

        token = JwtBuilder(self.user).build_token(expires_in=self.expires_in)
        self.assert_valid_jwt_access_token(token, self.user, self.scopes)

    def test_override_secret_and_audience(self):
        """
        Verify that the signing key and audience can be overridden.
        """
        secret = 'avoid-this'
        audience = 'avoid-this-too'

        token = JwtBuilder(
            self.user,
            secret=secret,
        ).build_token(
            expires_in=self.expires_in,
            aud=audience,
        )
        self.assert_valid_jwt_access_token(token,
                                           self.user,
                                           self.scopes,
                                           aud=audience,
                                           secret=secret)
Пример #6
0
    def test_get_id_token(self, has_profile):
        """Verify that ID tokens are signed with the correct secret and generated with the correct claims."""
        full_name = UserProfileFactory(
            user=self.user).name if has_profile else None

        token = get_id_token(self.user, self.client_name)

        payload = jwt.decode(
            token,
            self.oauth2_client.client_secret,
            audience=self.oauth2_client.client_id,
            issuer=settings.OAUTH_OIDC_ISSUER,
        )

        now = datetime.datetime.utcnow()
        expiration = now + datetime.timedelta(
            seconds=settings.OAUTH_ID_TOKEN_EXPIRATION)

        expected_payload = {
            'preferred_username': self.user.username,
            'name': full_name,
            'email': self.user.email,
            'administrator': self.user.is_staff,
            'iss': settings.OAUTH_OIDC_ISSUER,
            'exp': calendar.timegm(expiration.utctimetuple()),
            'iat': calendar.timegm(now.utctimetuple()),
            'aud': self.oauth2_client.client_id,
            'sub': anonymous_id_for_user(self.user, None),
        }

        self.assertEqual(payload, expected_payload)
Пример #7
0
    def setUp(self):
        super(I18nLangPrefTests, self).setUp()
        # Create one user and save it to the database
        email = '*****@*****.**'
        pwd = 'test_password'
        self.user = UserFactory.build(username='******', email=email)
        self.user.set_password(pwd)
        self.user.save()

        # Create a registration for the user
        RegistrationFactory(user=self.user)

        # Create a profile for the user
        UserProfileFactory(user=self.user)

        # Create the test client
        self.client = Client()

        # Get the login url & log in our user
        try:
            login_url = reverse('login_post')
        except NoReverseMatch:
            login_url = reverse('login')
        self.client.post(login_url, {'email': email, 'password': pwd})

        # Url and site lang vars for tests to use
        self.url = reverse('dashboard')
        self.site_lang = settings.LANGUAGE_CODE
Пример #8
0
    def test_create_cert_pdf_allow_certificate_is_false_with_noop(
            self, gen_mock, grade_mock, profile_mock, white_mock, hash_mock,
            cert_mock):

        cert_dummy = MagicMock()
        profile_mock.return_value = UserProfileFactory.build(
            user=self.student, allow_certificate=False)
        white_mock().exists = lambda: True
        gen_mock.return_value = (cert_dummy, True)
        grade_mock.return_value = self.grade
        course_mock = MagicMock()

        cert = CertificatePDF(self.user, self.course_id, self.debug, True,
                              self.file_prefix, self.exclude)
        cert._create_cert_pdf(self.student, self.request, course_mock)

        gen_mock.assert_called_once_with(course_id=self.course_id,
                                         user=self.student)
        grade_mock.assert_called_with(ANY, self.request, course_mock)
        profile_mock.assert_called_once_with(user=self.student)
        white_mock.assert_called_with(user=self.student,
                                      course_id=self.course_id,
                                      whitelist=True)
        self.assertEqual(cert_dummy.save.call_count, 0)
        self.assertEqual(cert_dummy.status, CertificateStatuses.restricted)
Пример #9
0
    def setUp(self):
        super(TestIdTokenGeneration, self).setUp()

        self.oauth2_client = ClientFactory(name=self.client_name,
                                           client_type=CONFIDENTIAL)
        self.user = UserFactory()

        # Create a profile for the user
        self.user_profile = UserProfileFactory(user=self.user)
Пример #10
0
    def setUp(self):
        """Setup a test user along with its registration and profile"""
        super(LoginTest, self).setUp()
        self.user = self._create_user(self.username, self.user_email)

        RegistrationFactory(user=self.user)
        UserProfileFactory(user=self.user)

        self.client = Client()
        cache.clear()

        self.url = reverse('login_api')
Пример #11
0
    def setUp(self):
        super(TestPasswordVerificationView, self).setUp()
        self.user = UserFactory.build(username='******', is_active=True)
        self.password = '******'
        self.user.set_password(self.password)
        self.user.save()
        # Create a registration for the user
        RegistrationFactory(user=self.user)

        # Create a profile for the user
        UserProfileFactory(user=self.user)

        # Create the test client
        self.client = Client()
        cache.clear()
        self.url = reverse('verify_password')
Пример #12
0
    def setUp(self):
        """Setup a test user along with its registration and profile"""
        super(LoginTest, self).setUp()
        self.user = UserFactory.build(username=self.username, email=self.user_email)
        self.user.set_password(self.password)
        self.user.save()

        RegistrationFactory(user=self.user)
        UserProfileFactory(user=self.user)

        self.client = Client()
        cache.clear()

        try:
            self.url = reverse('login_post')
        except NoReverseMatch:
            self.url = reverse('login')
Пример #13
0
    def setUp(self):
        # Create one user and save it to the database
        self.user = UserFactory.build(username='******', email='*****@*****.**')
        self.user.set_password('test_password')
        self.user.save()

        # Create a registration for the user
        RegistrationFactory(user=self.user)

        # Create a profile for the user
        UserProfileFactory(user=self.user)

        # Create the test client
        self.client = Client()
        cache.clear()

        # Store the login url
        try:
            self.url = reverse('login_post')
        except NoReverseMatch:
            self.url = reverse('login')
Пример #14
0
    def test_create_cert_pdf_allow_certificate_is_false_with_noop(
            self, gen_mock, grade_mock, profile_mock, white_mock,
            hash_mock, cert_mock):

        cert_dummy = MagicMock()
        profile_mock.return_value = UserProfileFactory.build(
            user=self.student, allow_certificate=False)
        white_mock().exists = lambda: True
        gen_mock.return_value = (cert_dummy, True)
        grade_mock.return_value = self.grade
        course_mock = MagicMock()

        cert = CertificatePDF(self.user, self.course_id, self.debug,
                              True, self.file_prefix, self.exclude)
        cert._create_cert_pdf(self.student, self.request, course_mock)

        gen_mock.assert_called_once_with(course_id=self.course_id, user=self.student)
        grade_mock.assert_called_with(ANY, self.request, course_mock)
        profile_mock.assert_called_once_with(user=self.student)
        white_mock.assert_called_with(
            user=self.student, course_id=self.course_id, whitelist=True)
        self.assertEqual(cert_dummy.save.call_count, 0)
        self.assertEqual(cert_dummy.status, CertificateStatuses.restricted)
Пример #15
0
    def setUp(self):
        super(TestJwtBuilder, self).setUp()

        self.user = UserFactory()
        self.profile = UserProfileFactory(user=self.user)
Пример #16
0
 def setUp(self):
     super(CertificateTests, self).setUp()
     self.course = CourseFactory.create()
     UserProfileFactory.create(user=self.user)
Пример #17
0
 def set_user(self, user):
     super(BaseTestMixin, self).set_user(user)
     self.profile = UserProfileFactory(user=self.user)
Пример #18
0
 def setUp(self):
     super(CertificateTests, self).setUp()
     self.course = CourseFactory.create()
     UserProfileFactory.create(user=self.user)
Пример #19
0
    def setUp(self):
        super(TestJwtBuilder, self).setUp()

        self.user = UserFactory()
        self.profile = UserProfileFactory(user=self.user)
Пример #20
0
    def setUp(self):
        super(TestDeprecatedJwtBuilder, self).setUp()

        self.user = UserFactory()
        self.profile = UserProfileFactory(user=self.user)
        self.scopes = ['email', 'profile']