def _make_request(self, method='get', program_id=None, complete=False, data=None, admin=False): """ DRY helper. """ token = self.generate_id_token(UserFactory(), admin=admin) auth = 'JWT {0}'.format(token) if program_id is not None: url = reverse('api:v1:programs-detail', kwargs={'pk': program_id}) elif complete: url = reverse('api:v1:programs-complete') else: url = reverse('api:v1:programs-list') content_type = 'application/json' if method == 'patch': data = json.dumps(data) content_type = 'application/merge-patch+json' elif method in ['post', 'put']: data = json.dumps(data) return getattr(self.client, method)(url, data=data, HTTP_AUTHORIZATION=auth, content_type=content_type)
def get_authenticated_client(self, role_name): """ Helper for concisely obtaining a `rest_framework.test.APIClient` instance, authenticated with a user having some specific role. """ # create a user with the specified role user = UserFactory.create() user.groups.add(Group.objects.get(name=role_name)) # pylint: disable=no-member # create an APIClient and force auth client = APIClient() client.force_authenticate(user) return client
def test_required_claims(self, claim): """ Verify that tokens that do not carry 'exp' or 'iat' claims are rejected """ authentication = JwtAuthentication() user = UserFactory() jwt_payload = self.default_payload(user) del jwt_payload[claim] jwt_value = self.generate_token(jwt_payload) request = APIRequestFactory().get( 'dummy', HTTP_AUTHORIZATION='JWT {}'.format(jwt_value)) with self.assertRaises(AuthenticationFailed): authentication.authenticate(request)
def test_leeway(self, claim, offset): """ Verify that the service allows the specified amount of leeway (in seconds) when nonzero and validating "exp" and "iat" claims. """ authentication = JwtAuthentication() user = UserFactory() jwt_value = self.generate_id_token( user, **{claim: int(time.time()) + offset}) request = APIRequestFactory().get( 'dummy', HTTP_AUTHORIZATION='JWT {}'.format(jwt_value)) # with no leeway, these requests should not be authenticated with mock.patch.object(drf_jwt_settings, 'JWT_LEEWAY', 0): with self.assertRaises(AuthenticationFailed): authentication.authenticate(request) # with enough leeway, these requests should be authenticated with mock.patch.object(drf_jwt_settings, 'JWT_LEEWAY', abs(offset)): self.assertEqual((user, jwt_value), authentication.authenticate(request))
def setUp(self): self.user = UserFactory.create() super(TestPipelineUserRoles, self).setUp()