def test_set_country_override_invalid(self): request = self.factory.get("/?{}=Wrong".format( settings.SCHEMA_OVERRIDE_PARAM )) with mock.patch(PATH_SET_TENANT, self.mock_set): utils.set_country(self.user, request) self.assertEqual(request.tenant, self.country) self.mock_set.assert_called_with(self.country)
def authenticate(self, request): super_return = super().authenticate(request) if not super_return: return None user, token = super_return set_country(user, request) return user, token
def test_set_country_override_not_available(self): """Ideally we would be setup a different country But having issues creating another country outside of current schema """ self.user.profile.countries_available.remove(self.country) request = self.factory.get("/?{}={}".format( settings.SCHEMA_OVERRIDE_PARAM, self.country.name )) with mock.patch(PATH_SET_TENANT, self.mock_set): utils.set_country(self.user, request) self.assertEqual(request.tenant, self.country) self.mock_set.assert_called_with(self.country)
def process_request(self, request): # Connection needs first to be at the public schema, as this is where # the tenant metadata is stored. connection.set_schema_to_public() if not request.user: return None if INACTIVE_WORKSPACE_URL in request.path: return None if request.user.is_anonymous: # check if user is trying to reach an authentication endpoint if any(fragment in request.path for fragment in ANONYMOUS_ALLOWED_URL_FRAGMENTS): return None # let them pass else: return HttpResponseRedirect(settings.LOGIN_URL) if request.user.is_superuser and not request.user.profile.country: return None if not request.user.is_superuser and ( not request.user.profile.country or request.user.profile.country.business_area_code in settings.INACTIVE_BUSINESS_AREAS): return HttpResponseRedirect("/workspace_inactive/") try: set_country(request.user, request) except Exception: logger.info('No country found for user {}'.format(request.user)) return SimpleTemplateResponse('no_country_found.html', {'user': request.user}) # Content type can no longer be cached as public and tenant schemas # have different models. If someone wants to change this, the cache # needs to be separated between public and shared schemas. If this # cache isn't cleared, this can cause permission problems. For example, # on public, a particular model has id 14, but on the tenants it has # the id 15. if 14 is cached instead of 15, the permissions for the # wrong model will be fetched. ContentType.objects.clear_cache() # Do we have a public-specific urlconf? if hasattr( settings, 'PUBLIC_SCHEMA_URLCONF' ) and request.tenant.schema_name == get_public_schema_name(): request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
def get(self, request, format=None): try: workspace = Workspace.objects.get(name=request.query_params.get('country').title()) except (Workspace.DoesNotExist, AttributeError): return Response(status=400, data={'error': 'Country not found'}) try: p = ProgrammeSynchronizer(workspace) p.sync() except BaseException as e: set_country(request.user, request) return Response(status=500, data=str(e)) set_country(request.user, request) return Response({'success': 'Country = {}'.format(workspace.name)})
def get(self, request, format=None): try: workspace = Workspace.objects.get( name=request.query_params.get('country').title()) except (Workspace.DoesNotExist, AttributeError): return Response(status=400, data={'error': 'Country not found'}) try: p = ProgrammeSynchronizer(workspace) p.sync() except BaseException as e: set_country(request.user, request) return Response(status=500, data=str(e)) set_country(request.user, request) return Response({'success': 'Country = {}'.format(workspace.name)})
def process_request(self, request): # Connection needs first to be at the public schema, as this is where # the tenant metadata is stored. connection.set_schema_to_public() if not request.user: return None if INACTIVE_WORKSPACE_URL in request.path: return None if request.user.is_anonymous: # check if user is trying to reach an authentication endpoint if any(fragment in request.path for fragment in ANONYMOUS_ALLOWED_URL_FRAGMENTS): return None # let them pass else: return HttpResponseRedirect(settings.LOGIN_URL) if request.user.is_superuser and not request.user.profile.country: return None if not request.user.is_superuser and ( not request.user.profile.country or request.user.profile.country.business_area_code in settings.INACTIVE_BUSINESS_AREAS): return HttpResponseRedirect("/workspace_inactive/") try: set_country(request.user, request) except Exception: logger.info('No country found for user {}'.format(request.user)) return SimpleTemplateResponse('no_country_found.html', {'user': request.user}) # Content type can no longer be cached as public and tenant schemas # have different models. If someone wants to change this, the cache # needs to be separated between public and shared schemas. If this # cache isn't cleared, this can cause permission problems. For example, # on public, a particular model has id 14, but on the tenants it has # the id 15. if 14 is cached instead of 15, the permissions for the # wrong model will be fetched. ContentType.objects.clear_cache() # Do we have a public-specific urlconf? if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF') and request.tenant.schema_name == get_public_schema_name(): request.urlconf = settings.PUBLIC_SCHEMA_URLCONF
def authenticate(self, request): jwt_value = self.get_jwt_value(request) if jwt_value is None: # no JWT token return to skip this authentication mechanism return None try: user, jwt_value = super().authenticate(request) except TypeError: raise PermissionDenied(detail='No valid authentication provided') except AuthenticationFailed: # Try again if getattr(settings, 'JWT_ALLOW_NON_EXISTENT_USERS', False): try: # try and see if the token is valid payload = jwt_decode_handler(jwt_value) except (jwt.ExpiredSignature, jwt.DecodeError): raise PermissionDenied(detail='Authentication Failed') else: # signature is valid user does not exist... setting default authenticated user user = get_user_model().objects.get( username=settings.DEFAULT_UNICEF_USER) setattr(user, 'jwt_payload', payload) else: raise PermissionDenied(detail='Authentication Failed') if not user.profile.country: raise PermissionDenied(detail='No country found for user') if user.profile.country_override and user.profile.country != user.profile.country_override: user.profile.country = user.profile.country_override user.profile.save() set_country(user, request) return user, jwt_value
def test_set_country(self): request = self.factory.get("/") with mock.patch(PATH_SET_TENANT, self.mock_set): utils.set_country(self.user, request) self.assertEqual(request.tenant, self.country) self.mock_set.assert_called_with(self.country)