def get_used_flavors_summary_queryset(user): reseller_resources = user_reseller_resources(user=user) return Instance.objects.filter( project__service__client__reseller_resources=reseller_resources ).values('flavor').annotate(count=Count('id')).exclude( status=InstanceStatus.DELETED).exclude( terminated_at__isnull=False).order_by()
def hide_for_clients(self, request, pk): del request, pk # unused flavor = self.get_object() reseller_resources = user_reseller_resources(self.request.user) flavor.used_by_resellers.remove(reseller_resources) flavor.save() return Response({'detail': _('Flavor will be hidden for clients')})
def perform_destroy(self, user: AppUser): pk = user.id if user == self.request.user: raise APIBadRequest( _('Cannot delete the user you are logged in with.')) # Do not allow editing of users not assigned to reseller reseller_resources = user_reseller_resources(self.request.user) if user.reseller_resources != reseller_resources: raise PermissionDenied with transaction.atomic(): if user.permissions: user.permissions.delete() user.delete() user = self.request.user reseller_delete_user.send( sender=__name__, user=user, user_id=user.id, deleted_user_name=user.username, deleted_user_id=pk, username=user.username, request=self.request, )
def get_display_for_clients(self, flavor: OpenstackInstanceFlavor): reseller_resources = user_reseller_resources( self.context['request'].user) if flavor.used_by_resellers.filter(id=reseller_resources.id).first(): return True else: return False
def has_permission(self, request, view): if request.user and request.user.is_reseller: if user_reseller_resources(user=request.user): match_session_ip_or_401(request) return True raise exceptions.AuthenticationFailed()
def is_manageable_by_reseller(user, db_image: Image, message): reseller_resources = user_reseller_resources(user=user) manageable = False try: if db_image.reseller_resources == reseller_resources: manageable = True if (not manageable and db_image.project.service and (db_image.project.service.client.reseller_resources and db_image.project.service.client.reseller_resources == reseller_resources)): manageable = True if (not manageable and 'image_type' in db_image.properties and db_image.properties['image_type'] == 'snapshot'): # if snapshot, first check if related instance is related to the reseller resources if 'instance_uuid' in db_image.properties: related_instance = Instance.objects.filter( id=db_image.properties['instance_uuid']).first() if related_instance: if related_instance.project.service.client.reseller_resources == reseller_resources: manageable = True except Exception: raise ForbiddenException( _('Could not determine if image is related to reseller service.' )) if not manageable: raise ForbiddenException(message)
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if not validate_cloud_objects_limit(): raise APIBadRequest(_('Licence cloud objects limit reached. Please check your license.')) try: os_image_api = Images(api_session=self.os_admin_api.session) image = os_image_api.create(owner=self.os_admin_api.project_id, **serializer.validated_data) except Exception as e: LOG.error(e) handle(self.request, message='Unable to create the image') else: headers = self.get_success_headers(serializer.data) data = serializer.data data['id'] = image.id reseller_resources = user_reseller_resources(self.request.user) if reseller_resources: Image.objects.update_or_create( defaults={ 'reseller_resources': reseller_resources, 'min_disk': serializer.validated_data.get('min_disk', 0), 'min_ram': serializer.validated_data.get('min_ram', 0), 'region': serializer.validated_data.get('region') }, id=image.id, ) return Response(data, status=status.HTTP_201_CREATED, headers=headers)
def get_snapshots_for_instance(self, request): instance_uuid = request.GET.get('instance_uuid', None) reseller_resources = user_reseller_resources(user=self.request.user) volume_attachments = VolumeAttachments.objects.filter(server_id=instance_uuid).values('volume_id') volumes = Volume.objects.filter(id__in=volume_attachments) volume_snapshots_qs = VolumeSnapshot.objects.filter(volume__in=volumes) if reseller_resources: volume_snapshots_qs = volume_snapshots_qs.filter( project__service__client__reseller_resources=reseller_resources ) volume_snapshots_count = volume_snapshots_qs.count() volume_snapshots_uuids = volume_snapshots_qs.values('id') image_snapshots = Image.objects.filter( Q(volume_snapshot_uuid__in=volume_snapshots_uuids) | Q(instance_uuid=instance_uuid) ) if reseller_resources: image_snapshots = image_snapshots.filter( Q(reseller_resources=reseller_resources) | Q(project__service__client__reseller_resources=reseller_resources) ) serializer = StaffImageSerializer(image_snapshots, many=True) return Response({ 'objects': serializer.data, 'volume_snapshots_count': volume_snapshots_count, })
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) queryset = super().get_queryset().filter( project__service__client__reseller_resources=reseller_resources, ).all() return queryset
def display_for_clients(self, request, pk): del request, pk # unused flavor = self.get_object() reseller_resources = user_reseller_resources(self.request.user) flavor.used_by_resellers.add(reseller_resources) flavor.save() return Response({'detail': _('Flavor will be displayed for clients')})
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) queryset = super().get_queryset().filter( Q(project__service__client__reseller_resources=reseller_resources) | Q(reseller_resources=reseller_resources) | (Q(visibility=OpenStackImageVisibility.PUBLIC) & Q(reseller_resources=None)), ).all() return queryset
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) return ServiceDynamicUsage.objects.filter( Q( service__client__reseller_resources=reseller_resources ) | Q( reseller_service__client__reseller_resources=reseller_resources ) ).order_by('service__status')
def perform_create(self, serializer): serializer.validated_data[ 'reseller_resources'] = user_reseller_resources( user=self.request.user) serializer.is_valid(raise_exception=True) try: serializer.save() except IntegrityError: raise ValidationError( {'name': 'A configuration with this name already exists'})
def get_queryset(self): queryset = PricingRule.objects.all() if not reseller_active_features.is_enabled( 'openstack.instances.traffic'): traffic_resource = BillingResource.objects.filter( name='instance_traffic').first() queryset = queryset.exclude(resource=traffic_resource).all() reseller_resources = user_reseller_resources(user=self.request.user) return queryset.filter(plan__reseller_resources=reseller_resources)
def summary(self, request): del request # unused reseller_resources = user_reseller_resources(self.request.user) invoices = Invoice.objects.filter( client__reseller_resources=reseller_resources) invoice_info = { 'paid': invoices.filter(status='Paid').count(), 'unpaid': invoices.filter(status='Unpaid').count(), 'cancelled': invoices.filter(status='Cancelled').count(), 'refunded': invoices.filter(status='Refunded').count() } return Response(invoice_info)
def summary(self, request): del request # unused reseller_resources = user_reseller_resources(self.request.user) client_info = { 'count': Client.objects.filter( reseller_resources=reseller_resources).count(), 'new': Client.objects.filter( date_created__gt=utcnow() - datetime.timedelta(days=2), reseller_resources=reseller_resources).count() } return Response(client_info)
def get_configurations_for_client(self, request, pk): del request, pk # unused client = self.get_object() reseller_resources = user_reseller_resources(self.request.user) configurations = Configuration.objects.filter( reseller_resources=reseller_resources).exclude( id=client.configuration_id) return Response({ 'configurations': [{ 'id': config.id, 'name': config.name } for config in configurations] })
def get_users_not_in_client(self, request, pk): del pk # unused """Retrieve regular active users without any client associated to them""" self.get_object() # Checks permissions reseller_resources = user_reseller_resources(request.user) users = get_user_model().objects.filter( is_active=True, is_staff=False, is_reseller=False, clients__isnull=True, reseller_resources=reseller_resources, ) return Response( {'users': UserMinSerializer(instance=users, many=True).data})
def validate(self, attrs): validated_data = super().validate(attrs) request = self.context.get('request', None) if not request: raise ValidationError({'detail': _('Internal error when creating user.')}) else: # user created by reseller should be assigned to creating reseller validated_data['reseller_resources'] = user_reseller_resources(user=request.user) validated_data['is_reseller'] = False validated_data['is_staff'] = False validated_data['is_superuser'] = False return validated_data
def create_snapshot(self, request, id): create_snapshot_as_client = request.data.pop('create_snapshot_as_client', False) serializer = InstanceNameSerializer(data=request.data) serializer.is_valid(raise_exception=True) if create_snapshot_as_client: instance = self.get_object() try: project = instance.project except instance.project.DoesNotExist: raise APIBadRequest(_('Instance is not related to any project. Aborting.')) custom_api_session = IdentityUserApi( project.project_id, project.project_domain_id, cache=request.session ).session instances_api = Instances(api_session=custom_api_session) instance_user_api = instances_api.get(db_instance=instance) try: image_uuid = instance_user_api.create_snapshot(name=serializer.validated_data['name']) return Response({'image_uuid': image_uuid}) except Exception as e: LOG.error(e) msg = _('Unable to create snapshot for instance {0}').format(instance.name) handle(self.request, message=msg) else: instance = self.get_instance() try: image_uuid = instance.create_snapshot(name=serializer.validated_data['name']) reseller_resources = user_reseller_resources(self.request.user) if reseller_resources: Image.objects.update_or_create( defaults={ 'reseller_resources': reseller_resources, 'min_disk': 0, 'min_ram': 0, 'region': OpenstackRegion.objects.get(id=instance.instance.region) }, id=image_uuid, ) return Response({'image_uuid': image_uuid}) except Exception as e: LOG.error(e) msg = _('Unable to create snapshot for instance {0}').format(instance.instance.name) handle(self.request, message=msg)
def change_configuration(self, request, pk): del pk # unused serializer = ConfigurationIdSerializer(data=request.data) serializer.is_valid(raise_exception=True) client = self.get_object() reseller_resources = user_reseller_resources(self.request.user) try: config = Configuration.objects.get( pk=serializer.validated_data['configuration'], reseller_resources=reseller_resources, ) except Configuration.DoesNotExist: raise ObjectNotFound({'detail': _('Configuration does not exist')}) client.configuration = config client.save(update_fields=['configuration']) return Response({'detail': _('Ok')})
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) if self.action in [ 'list', 'retrieve', 'display_for_clients', 'hide_for_clients' ]: queryset = super().get_queryset().filter( Q(reseller_resources=reseller_resources) | Q( reseller_resources__isnull=True, show_in_fleio=True, is_public=True, disabled=False, ), ) else: queryset = super().get_queryset().filter( reseller_resources=reseller_resources, ) return queryset.order_by('-reseller_resources', 'memory_mb', 'id')
def process_request(self, request): if request.user.is_anonymous or request.user.is_staff: return None path_resolved = resolve(request.path_info) if len(path_resolved.namespaces) and path_resolved.namespaces[0] == 'staff': return None if path_resolved.url_name not in self.whitelisted_url_names: if request.user.clients.count() == 0: # NOTE(tomo): "clientRequired" is used by frontend to make sure the error is a client required error return JsonResponse({'detail': _('Client billing information is required to fulfill the request'), 'clientRequired': True}, status=status.HTTP_428_PRECONDITION_REQUIRED) if request.user.is_reseller and (request.method == 'POST' or request.method == 'DELETE' or request.method == 'PUT' or request.method == 'PATCH'): # if user is a reseller and his client is suspended do not allow him to do any important action reseller_resources = user_reseller_resources(user=request.user) if reseller_resources.service and not reseller_resources.service.is_active(): return JsonResponse({ 'detail': _('Your client is suspended.') }, status=status.HTTP_403_FORBIDDEN)
def impersonate(self, request, pk): user = get_object_or_404(get_user_model(), pk=pk, is_active=True, is_staff=False) request.session['impersonate'] = user.pk user_impersonated.send(sender=__name__, user=request.user, username=request.user.username, user_id=request.user.pk, impersonated_user_name=user.username, impersonated_user_id=user.pk, request=request) reseller_resources = user_reseller_resources(request.user) enduser_panel_url = reseller_resources.enduser_panel_url if reseller_resources else None return Response({ 'detail': _('User {} impersonated').format(user.username), 'enduser_panel_url': enduser_panel_url })
def login(request): serializer = LoginSerializer(data={ 'username': request.data.get('username', ''), 'password': request.data.get('password', ''), 'remember_me': request.data.get('remember_me', False), }) serializer.is_valid(raise_exception=True) data = serializer.validated_data user = auth.authenticate(username=data['username'], password=data['password']) ip = get_ip(request) if user is None or not user.is_reseller: if user is None: UserModel = auth.get_user_model() try: matched_user = UserModel.objects.get(username=data['username']) except UserModel.DoesNotExist: # reseller user does not exists LOG.info('User {} not found in database'.format(data['username'])) else: if matched_user.is_reseller: LOG.info('Login failed for user {}.'.format(data['username'])) else: LOG.info('Login denied for user {}.'.format(data['username'])) else: if not user.is_reseller: LOG.info('Login denied for user {}.'.format(data['username'])) raise AuthenticationFailed(detail=_('Incorrect user name or password')) elif not user.is_active: LOG.info('Inactive user {} login attempted.'.format(data['username'])) raise AuthenticationFailed(detail=_('This account is inactive')) elif not user_reseller_resources(user): LOG.info('User {} login attempted, but user is not associated with a reseller.'.format(data['username'])) raise AuthenticationFailed(detail=_('This account is not associated with a reseller client')) else: try: sfa_completed, remember_sfa_token = process_login_with_sfa(request=request) except Exception as e: raise e if not sfa_completed: sfa_required, response = check_sfa_required_and_get_settings(user=user) if sfa_required: return response auth.login(request, user) if request.session.test_cookie_worked(): request.session.delete_test_cookie() if data['remember_me']: request.session.set_expiry(2 * 365 * 30 * 24 * 60 * 60) # two years else: request.session.set_expiry(0) request.session['ip'] = ip reseller_logged_in.send( sender=__name__, user=user, user_id=user.pk, username=user.username, email=user.email, request=request ) response_dict = { 'user': get_current_user_info(request.user), 'features': reseller_active_features.all, 'version': VERSION, 'is_white_label': is_white_label_license() } if remember_sfa_token: response_dict['remember_sfa_token'] = remember_sfa_token return Response(response_dict)
def projects_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) return Project.objects.filter( service__client__reseller_resources=reseller_resources)
def perform_create(self, serializer): serializer.validated_data[ 'reseller_resources'] = user_reseller_resources( user=self.request.user) serializer.save()
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) return super().get_queryset().filter( Q(user=self.request.user) | Q(user__reseller_resources=reseller_resources), ).all()
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) return ServiceDynamicUsageHistory.objects.filter( service_dynamic_usage__service__client__reseller_resources= reseller_resources)
def get_queryset(self): reseller_resources = user_reseller_resources(user=self.request.user) return ConfigurableOptionCycle.objects.filter( option__reseller_resources=reseller_resources).all()