Пример #1
0
 def authorize_user(self, user):
     url = reverse("login_obtain_jwt_pair")
     resp = self.client.post(
         url,
         {"username": user.username, "password": get_default_password()},
         format="json",
     )
     token = resp.data["access"]
     self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")
    def test_refresh_token_after_ban(self):
        user = create_user()
        login_url = reverse("login_obtain_jwt_pair")
        refresh_url = reverse("login_refresh_jwt_token")

        # Login and blacklisted the refresh token
        # to test exception handling in signals.py
        response = self.client.post(
            login_url,
            {
                "username": user.username,
                "password": get_default_password()
            },
            format="json",
        )
        token = RefreshToken(response.data["refresh"])
        token.blacklist()

        # Login again and try the main flow
        response = self.client.post(
            login_url,
            {
                "username": user.username,
                "password": get_default_password()
            },
            format="json",
        )
        access_token = response.data["access"]
        refresh_token = response.data["refresh"]

        self.authorize_user(self.admin)

        response = self.client.post(f"{self.url}/{user.id}/ban")
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.check_if_user_is_banned(user.id, True)

        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}")
        response = self.client.post(refresh_url, {"refresh": refresh_token},
                                    format="json")
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(str(response.data["detail"]), "Token is blacklisted")
Пример #3
0
    def test_logout_other_account(self):
        login_url = reverse("login_obtain_jwt_pair")
        logout_url = reverse("logout")

        # Create two users
        u1 = create_user()
        u2 = create_user()

        # Login to both users
        resp_u1 = self.client.post(
            login_url,
            {
                "username": u1.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp_u1.status_code, status.HTTP_200_OK)
        resp_u2 = self.client.post(
            login_url,
            {
                "username": u2.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp_u2.status_code, status.HTTP_200_OK)

        # Set tokens
        access_token_u1 = resp_u1.data["access"]
        refresh_token_u2 = resp_u2.data["refresh"]

        # When the user tries to logout using another user's refresh token an error should occur
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token_u1}")
        resp = self.client.post(logout_url, {"refresh": refresh_token_u2},
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(resp.data["detail"], "Token is invalid or expired")
 def check_login_failed_when_banned(self, user):
     url = reverse("login_obtain_jwt_pair")
     response = self.client.post(
         url,
         {
             "username": user.username,
             "password": get_default_password()
         },
         format="json",
     )
     self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
     self.assertEqual(
         str(response.data["detail"]),
         "No active account found with the given credentials",
     )
Пример #5
0
    def setUp(self):
        self.url = "/api/v1/admin/requests"
        self.user = create_user(is_admin=True)
        url = reverse("login_obtain_jwt_pair")
        resp = self.client.post(
            url,
            {
                "username": self.user.username,
                "password": get_default_password()
            },
            format="json",
        )
        token = resp.data["access"]
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token}")

        self.request1 = create_request(100,
                                       self.user,
                                       start="2020-03-10T19:30:00+0100")
        self.request2 = create_request(101,
                                       self.user,
                                       start="2020-07-07T19:30:00+0100")
        self.request3 = create_request(102,
                                       self.user,
                                       start="2020-12-24T19:30:00+0100")

        self.video1 = create_video(200, self.request1)
        self.video2 = create_video(201, self.request2)
        self.video2.additional_data = {
            "aired": [
                "2020-01-12",
                "2019-11-25",
                "2020-10-25",
                "2018-05-19",
                "2020-07-14",
            ]
        }
        self.video2.save()
        self.video3 = create_video(202, self.request3)
        self.video3.additional_data = {
            "aired": [
                "2019-03-03",
                "2020-04-04",
                "2018-02-02",
            ],
            "length": 152,
        }
        self.video3.save()
Пример #6
0
    def test_logout(self):
        login_url = reverse("login_obtain_jwt_pair")
        refresh_url = reverse("login_refresh_jwt_token")
        logout_url = reverse("logout")

        # Create a user
        u = create_user()

        # Login and check all data is present
        resp = self.client.post(
            login_url,
            {
                "username": u.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)

        # Set tokens
        access_token = resp.data["access"]
        refresh_token = resp.data["refresh"]

        # Try to logout without token in header
        resp = self.client.post(logout_url, {"refresh": refresh_token},
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(resp.data["detail"],
                         "Authentication credentials were not provided.")

        # Set Header and try again
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}")
        resp = self.client.post(logout_url, {"refresh": refresh_token},
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_205_RESET_CONTENT)

        # Try to get new access token with blacklisted refresh token
        resp = self.client.post(refresh_url, {"refresh": refresh_token},
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(resp.data["detail"], "Token is blacklisted")
Пример #7
0
    def test_login(self):
        url = reverse("login_obtain_jwt_pair")
        password = get_default_password()

        # Create inactive user
        u = create_user()
        u.is_active = False
        u.save()

        # Try login with e-mail - Should return error
        resp = self.client.post(url, {
            "email": u.email,
            "password": password
        },
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)

        # Try login with username (still inactive) - Should return error
        resp = self.client.post(url, {
            "username": u.username,
            "password": password
        },
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)

        # Set user to active
        u.is_active = True
        u.save()

        # Try login with active profile - Should return the JWT token
        resp = self.client.post(url, {
            "username": u.username,
            "password": password
        },
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)
Пример #8
0
    def test_token_refresh(self):
        login_url = reverse("login_obtain_jwt_pair")
        refresh_url = reverse("login_refresh_jwt_token")

        # Create a user
        u = create_user()

        # Create test request for the user
        r = create_request(101, u)

        # Login and check all data is present
        resp = self.client.post(
            login_url,
            {
                "username": u.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)

        # Set access token
        access_token = resp.data["access"]
        refresh_token = resp.data["refresh"]
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}")

        # Check if token works and user can access request
        resp = self.client.get("/api/v1/requests/" + str(r.id))
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        # Wait for the token to expire
        sleep(10)

        # The user should not be able to get the request because of the expired token
        resp = self.client.get("/api/v1/requests/" + str(r.id))
        self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(resp.data["code"], "token_not_valid")

        # Use the refresh token for new access token
        resp = self.client.post(refresh_url, {"refresh": refresh_token},
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)
        self.assertNotEqual(resp.data["access"], access_token)
        self.assertNotEqual(resp.data["refresh"], refresh_token)

        # Set the new access token
        access_token = resp.data["access"]
        self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}")

        # Check if token work and user can access request
        resp = self.client.get("/api/v1/requests/" + str(r.id))
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        # The previous refresh token should be blacklisted
        resp = self.client.post(refresh_url, {"refresh": refresh_token},
                                format="json")
        self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(resp.data["detail"], "Token is blacklisted")
Пример #9
0
    def test_custom_jwt_claims(self):
        login_url = reverse("login_obtain_jwt_pair")
        groups = ["Group1", "Group2", "Group3", "Group4", "Group5"]
        u = create_user(groups=groups)

        # Login
        resp = self.client.post(
            login_url,
            {
                "username": u.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        # Check if token contains all custom information
        token = AccessToken(resp.data["access"])
        self.assertEqual(token.payload["name"],
                         u.get_full_name_eastern_order())
        self.assertEqual(token.payload["role"], "user")
        self.assertEqual(token.payload["avatar"], u.userprofile.avatar_url)
        for group in groups:
            self.assertIn(group, token.payload["groups"])

        # Set user as staff member
        u.is_staff = True
        u.save()

        # Get new token with new role
        resp = self.client.post(
            login_url,
            {
                "username": u.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        # Check if token contains all custom information
        token = AccessToken(resp.data["access"])
        self.assertEqual(token.payload["role"], "staff")

        # Set user admin
        grp = Group.objects.get_or_create(name="Administrators")[0]
        u.groups.add(grp)
        u.save()

        # Get new token with new role
        resp = self.client.post(
            login_url,
            {
                "username": u.username,
                "password": get_default_password()
            },
            format="json",
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)

        # Check if token contains all custom information
        token = AccessToken(resp.data["access"])
        self.assertEqual(token.payload["role"], "admin")