Example #1
0
    def update(self, instance, validated_data):
        request = self.context.get('request')

        if 'status' in validated_data:
            status_data = validated_data.pop('status')
            can_change = ComplianceReportPermissions.user_can_change_status(
                request.user,
                instance,
                new_fuel_supplier_status=status_data['fuel_supplier_status'].
                status if 'fuel_supplier_status' in status_data else None,
                new_analyst_status=status_data['analyst_status'].status
                if 'analyst_status' in status_data else None,
                new_director_status=status_data['director_status'].status
                if 'director_status' in status_data else None,
                new_manager_status=status_data['manager_status'].status
                if 'manager_status' in status_data else None)
            if not can_change:
                raise PermissionDenied('Invalid status change')

            if 'fuel_supplier_status' in status_data:
                instance.status.fuel_supplier_status = status_data[
                    'fuel_supplier_status']
                if instance.supplements is not None and instance.status.fuel_supplier_status.status in [
                        'Submitted'
                ]:
                    # supplemental note is required
                    if 'supplemental_note' not in validated_data:
                        raise serializers.ValidationError(
                            'supplemental note is required when submitting a '
                            'supplemental report')
                    instance.supplemental_note = validated_data.pop(
                        'supplemental_note')
            if 'analyst_status' in status_data:
                instance.status.analyst_status = status_data['analyst_status']
            if 'manager_status' in status_data:
                instance.status.manager_status = status_data['manager_status']
            if 'director_status' in status_data:
                instance.status.director_status = status_data[
                    'director_status']

            instance.status.save()

        if 'exclusion_agreement' in validated_data:
            agreement_data = validated_data.pop('exclusion_agreement')

            if instance.exclusion_agreement:
                ExclusionAgreementRecord.objects.filter(
                    exclusion_agreement=instance.exclusion_agreement).delete()

                exclusion_agreement = instance.exclusion_agreement

            if 'records' in agreement_data:
                records_data = agreement_data.pop('records')

                if not instance.exclusion_agreement:
                    exclusion_agreement = ExclusionAgreement.objects.create(
                        **agreement_data, compliance_report=instance)
                    instance.exclusion_agreement = exclusion_agreement

                for record_data in records_data:
                    record = ExclusionAgreementRecord.objects.create(
                        **record_data, exclusion_agreement=exclusion_agreement)
                    exclusion_agreement.records.add(record)
                    exclusion_agreement.save()

        if instance.status.fuel_supplier_status.status in ['Submitted'] and \
                not instance.has_snapshot:
            # Create a snapshot
            request = self.context.get('request')
            snap = dict(
                ExclusionReportDetailSerializer(instance,
                                                context=self.context).data)
            snap['version'] = 1  # to track deserialization version
            snap['timestamp'] = datetime.now()

            ComplianceReportSnapshot.objects.filter(
                compliance_report=instance).delete()
            ComplianceReportSnapshot.objects.create(
                compliance_report=instance,
                create_user=request.user,
                create_timestamp=datetime.now(),
                snapshot=snap)

        if request:
            instance.update_user = request.user

        instance.save()

        # all other fields are read-only
        return instance
Example #2
0
 def create(self, request, *args, **kwargs):
     if request.user.is_anonymous:
         raise PermissionDenied(
             "Only logged in users with accounts can create customer profiles"
         )
     return super().create(request, *args, **kwargs)
Example #3
0
 async def subscribe_todos_in_user(self, **kwargs):
     user:User = self.scope["user"]
     if user.is_anonymous:
         raise PermissionDenied()
     await self.todos_change_handler.subscribe(user=user.pk)
     return {}, status.HTTP_200_OK
Example #4
0
    def attach(self, request, *args, **kwargs):
        attached = False
        created = False
        modified = False
        parent = self.get_parent_object()
        relationship = getattr(parent, self.relationship)
        sub_id = request.DATA.get('id', None)
        data = request.DATA

        # Create the sub object if an ID is not provided.
        if not sub_id:
            try:
                response = self.create(request, *args, **kwargs)
                if response.status_code != status.HTTP_201_CREATED:
                    return response
                sub_id = response.data['id']
                data = response.data
                try:
                    location = response['Location']
                except KeyError:
                    location = None
                created = True
            except Exception:
                raise PermissionDenied()

        # Retrive the sub object (whether created or by ID).
        sub = get_object_or_400(self.model, pk=sub_id)

        # likewise with creation, we never try and update
        if not created:
            # Update the object to make sure the data is correct, but
            # verify we have permission to edit before trying to update
            if not check_user_access(request.user, self.model, 'change', sub,
                                     data):
                raise PermissionDenied()
            else:
                sub.__dict__.update(data)
                if sub.is_dirty:
                    sub.save()
                    modified = True

        # Verify we have permission to attach.
        if not check_user_access(request.user,
                                 self.parent_model,
                                 'attach',
                                 parent,
                                 sub,
                                 self.relationship,
                                 data,
                                 skip_sub_obj_read_check=created):
            raise PermissionDenied()

        # Attach the object to the collection.
        if sub not in relationship.all():
            relationship.add(sub)
            attached = True

        if created:
            headers = {}
            if location:
                headers['Location'] = location
            return Response(data,
                            status=status.HTTP_201_CREATED,
                            headers=headers)
        elif modified or attached:
            return Response(data, status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_204_NO_CONTENT)
Example #5
0
 def update(self, request, *args, **kwargs):
     profile = CreatorProfile.objects.get(pk=self.kwargs["pk"])
     if not request.user == profile.owner:
         raise PermissionDenied(
             "You have no permissions to edit this photographer profile")
     return super().update(request, *args, **kwargs)
Example #6
0
 def get_user(self, email):
     try:
         return User.objects.get(email=email)
     except User.DoesNotExist:
         raise PermissionDenied()
Example #7
0
 def get(self, request, user_id):
     if not request.user.is_authenticated or request.user.osu_user_id != user_id:
         raise PermissionDenied("You may only retrieve invites for the authenticated user.")
     invites = Invite.objects.select_related("leaderboard", "leaderboard__owner").filter(user_id=user_id)
     serialiser = UserInviteSerialiser(invites, many=True)
     return Response(serialiser.data)
Example #8
0
 def validate_group(self, group):
     if not group.is_member(self.context['request'].user):
         raise PermissionDenied(_('You are not a member of this group.'))
     return group
Example #9
0
 def create(self, request, *args, **kwargs):
     if request.user:
         raise PermissionDenied(detail='You already have an account')
     return super().create(request, args, kwargs)
Example #10
0
 def retrieve(self, request, *args, **kwargs):
     if not belongsToInstitution(request, self.get_object().institution):
         raise PermissionDenied(
             detail='User does not belong to the institution', code=None)
     return super(StudentViewSet, self).retrieve(request, *args, **kwargs)
Example #11
0
 def destroy(self, request, *args, **kwargs):
     if not isInstitutionAdmin(request, self.get_object().institution):
         raise PermissionDenied(detail='User is not an admin_user',
                                code=None)
     return super(StudentViewSet, self).destroy(request, *args, **kwargs)
Example #12
0
 def create(self, request, *args, **kwargs):
     if not isInstitutionAdmin(request, getUserInstitution(request)):
         raise PermissionDenied(detail='User is not an admin_user',
                                code=None)
     return super(StudentViewSet, self).create(request, *args, **kwargs)
Example #13
0
def get_discount(request):
    if request.user.is_anonymous:
        raise PermissionDenied()
    host = request.META['HTTP_HOST']
    user = request.user
    contract_type = request.query_params['contract_type']
    promo_str = request.query_params['promo']
    discount = check_and_get_discount(promo_str, contract_type, user)
    answer = {'discount': discount}
    if 'contract_id' in request.query_params:
        contract = Contract.objects.get(id=request.query_params['contract_id'])
        contract_details = contract.get_details()
        if host == EOSISH_URL:
            kwargs = ContractSerializer().get_details_serializer(
                contract.contract_type)().to_representation(contract_details)
            cost = contract_details.calc_cost_eos(
                kwargs, contract.network) * (100 - discount) / 100
            answer['discount_price'] = {
                'EOS': cost,
                'EOSISH': str(float(cost) * rate('EOS', 'EOSISH').value)
            }
        elif host == MY_WISH_URL:
            options_cost = 0
            if contract.contract_type in (5, 28) and contract_details.authio:
                options_cost += AUTHIO_PRICE_USDT * NET_DECIMALS['USDT']

            if contract.contract_type in VERIFICATION_CONTRACTS_IDS and contract_details.verification:
                options_cost += VERIFICATION_PRICE_USDT * NET_DECIMALS['USDT']

            cost = (contract.cost -
                    options_cost) * (100 - discount) / 100 + options_cost
            answer['discount_price'] = {
                'USDT':
                str(cost),
                'ETH':
                str(int(
                    int(cost) / 10**6 * rate('USDT', 'ETH').value * 10**18)),
                'WISH':
                str(
                    int(
                        int(cost) / 10**6 * rate('USDT', 'WISH').value *
                        10**18)),
                'BTC':
                str(int(int(cost) / 10**6 * rate('USDT', 'BTC').value *
                        10**8)),
                'TRX':
                str(int(int(cost) * rate('ETH', 'TRX').value)),
                'TRONISH':
                str(int(int(cost) * rate('ETH', 'TRX').value))
            }
        elif host == TRON_URL:
            kwargs = ContractSerializer().get_details_serializer(
                contract.contract_type)().to_representation(contract_details)
            cost = contract_details.calc_cost_tron(
                kwargs, contract.network) * (100 - discount) / 100

            answer['discount_price'] = {'TRX': int(cost), 'TRONISH': int(cost)}
        elif host == WAVES_URL:
            kwargs = ContractSerializer().get_details_serializer(
                contract.contract_type)().to_representation(contract_details)
            cost = contract_details.calc_cost(
                kwargs, contract.network) * (100 - discount) / 100
            answer['discount_price'] = {
                'USDT':
                str(cost),
                'ETH':
                str(int(
                    int(cost) / 10**6 * rate('USDT', 'ETH').value * 10**18)),
                'WISH':
                str(
                    int(
                        int(cost) / 10**6 * rate('USDT', 'WISH').value *
                        10**18)),
                'BTC':
                str(int(int(cost) / 10**6 * rate('USDT', 'BTC').value *
                        10**8)),
                'TRX':
                str(int(int(cost) * rate('ETH', 'TRX').value)),
                'TRONISH':
                str(int(int(cost) * rate('ETH', 'TRX').value))
            }
        else:
            kwargs = ContractSerializer().get_details_serializer(
                contract.contract_type)().to_representation(contract_details)
            cost = contract_details.calc_cost(
                kwargs, contract.network) * (100 - discount) / 100
            answer['discount_price'] = {
                'ETH':
                str(cost),
                'WISH':
                str(int(cost * rate('ETH', 'WISH').value)),
                'BTC':
                str(int(cost * rate('ETH', 'BTC').value)),
                'TRX':
                str(int(cost) / 10**18 * rate('ETH', 'TRX').value * 10**6),
                'TRONISH':
                str(int(cost) / 10**18 * rate('ETH', 'TRONISH').value * 10**6)
            }

    return Response(answer)
    def put(self, request, pk):
        # Update science metadata based on resourcemetadata.xml uploaded
        resource, authorized, user = view_utils.authorize(
            request,
            pk,
            needed_permission=ACTION_TO_AUTHORIZE.EDIT_RESOURCE,
            raises_exception=False)
        if not authorized:
            raise PermissionDenied()

        files = request.FILES.values()
        if len(files) == 0:
            error_msg = {
                'file':
                'No resourcemetadata.xml file was found to update resource '
                'metadata.'
            }
            raise ValidationError(detail=error_msg)
        elif len(files) > 1:
            error_msg = {
                'file': ('More than one file was found. Only one file, named '
                         'resourcemetadata.xml, '
                         'can be used to update resource metadata.')
            }
            raise ValidationError(detail=error_msg)

        scimeta = files[0]
        if scimeta.content_type not in self.ACCEPT_FORMATS:
            error_msg = {
                'file': ("Uploaded file has content type {t}, "
                         "but only these types are accepted: {e}.").format(
                             t=scimeta.content_type,
                             e=",".join(self.ACCEPT_FORMATS))
            }
            raise ValidationError(detail=error_msg)
        expect = 'resourcemetadata.xml'
        if scimeta.name != expect:
            error_msg = {
                'file':
                "Uploaded file has name {n}, but expected {e}.".format(
                    n=scimeta.name, e=expect)
            }
            raise ValidationError(detail=error_msg)

        # Temp directory to store resourcemetadata.xml
        tmp_dir = tempfile.mkdtemp()
        try:
            # Fake the bag structure so that GenericResourceMeta.read_metadata_from_resource_bag
            # can read and validate the system and science metadata for us.
            bag_data_path = os.path.join(tmp_dir, 'data')
            os.mkdir(bag_data_path)
            # Copy new science metadata to bag data path
            scimeta_path = os.path.join(bag_data_path, 'resourcemetadata.xml')
            shutil.copy(scimeta.temporary_file_path(), scimeta_path)
            # Copy existing resource map to bag data path
            # (use a file-like object as the file may be in iRODS, so we can't
            #  just copy it to a local path)
            resmeta_path = os.path.join(bag_data_path, 'resourcemap.xml')
            with open(resmeta_path, 'wb') as resmeta:
                storage = get_file_storage()
                resmeta_irods = storage.open(AbstractResource.sysmeta_path(pk))
                shutil.copyfileobj(resmeta_irods, resmeta)

            resmeta_irods.close()

            try:
                # Read resource system and science metadata
                domain = Site.objects.get_current().domain
                rm = GenericResourceMeta.read_metadata_from_resource_bag(
                    tmp_dir, hydroshare_host=domain)
                # Update resource metadata
                rm.write_metadata_to_resource(resource,
                                              update_title=True,
                                              update_keywords=True)
                create_bag_files(resource)
            except HsDeserializationDependencyException as e:
                msg = (
                    "HsDeserializationDependencyException encountered when updating "
                    "science metadata for resource {pk}; depedent resource was {dep}."
                )
                msg = msg.format(pk=pk, dep=e.dependency_resource_id)
                logger.error(msg)
                raise ValidationError(detail=msg)
            except HsDeserializationException as e:
                raise ValidationError(detail=e.message)

            resource_modified(resource, request.user, overwrite_bag=False)
            return Response(data={'resource_id': pk},
                            status=status.HTTP_202_ACCEPTED)
        finally:
            shutil.rmtree(tmp_dir)
Example #15
0
def raise_permission_error():
    raise PermissionDenied("User doesn't have permission for this action.")
Example #16
0
 def validate(self, data):
     if self.instance.user == self.instance.repository.owner:
         raise PermissionDenied(_('The owner role can\'t be changed.'))
     return data
Example #17
0
 def has_object_permission(self, request, view, obj):
     message = 'You are not owner'
     if obj.reseller == request.user:
         return True
     else:
         raise PermissionDenied(detail=message)
Example #18
0
def profile_view(request):
    site_name = request.META['HTTP_HOST']
    print('site is', site_name, flush=True)
    if request.user.is_anonymous:
        print('anonymous', flush=True)
        raise PermissionDenied()
    if site_name.startswith('cn'):
        site_name = site_name[2:]
    if site_name.startswith('local'):
        print('cut local')
        site_name = site_name[5:]
    if site_name.startswith('trondev'):
        site_name = site_name.replace('trondev', 'dev')
    if site_name == WAVES_URL:
        site_name = MY_WISH_URL
    if site_name == RUBIC_EXC_URL:
        site_name = SWAPS_URL
    site = SubSite.objects.get(site_name=site_name)
    user_balance = UserSiteBalance.objects.get(subsite=site, user=request.user)

    if request.user.email:
        user_name = request.user.email
    elif request.user.first_name or request.user.last_name:
        user_name = '{} {}'.format(request.user.first_name,
                                   request.user.last_name)
    else:
        user_name = request.user.username

    swaps_notifications = None
    swaps_notification_email = None
    swaps_notification_telegram_name = None
    swaps_notification_type = None

    swaps_notification_set = request.user.swapsnotificationdefaults_set.all()
    if swaps_notification_set:
        swaps_notification_set = swaps_notification_set.first()
        swaps_notification_email = swaps_notification_set.email
        swaps_notification_telegram_name = swaps_notification_set.telegram_name
        swaps_notification_type = swaps_notification_set.notification

    swaps_notifications = {
        'email': swaps_notification_email,
        'telegram_name': swaps_notification_telegram_name,
        'notification': swaps_notification_type
    }

    answer = {
        'username':
        user_name,
        'contracts':
        Contract.objects.filter(user=request.user).count(),
        'balance':
        str(user_balance.balance),
        'internal_address':
        user_balance.eth_address,
        'internal_btc_address':
        user_balance.btc_address,
        'use_totp':
        request.user.profile.use_totp,
        'is_social':
        request.user.profile.is_social,
        'id':
        request.user.id,
        'lang':
        request.user.profile.lang,
        'memo':
        user_balance.memo,
        'eos_address':
        'mywishcoming',
        'bnb_address':
        BINANCE_PAYMENT_ADDRESS,
        'tron_address':
        hex2tronwif(user_balance.tron_address)
        if user_balance.tron_address else '',
        'usdt_balance':
        str(
            int(
                int(user_balance.balance) / 10**18 *
                convert('WISH', 'USDT')['USDT'] * 10**6)),
        'is_swaps_admin':
        request.user.profile.is_swaps_admin,
        'swaps_notifications':
        swaps_notifications
    }
    return Response(answer)
Example #19
0
 def get(self, request, user_id):
     if not request.user.is_authenticated or request.user.osu_user_id != user_id:
         raise PermissionDenied("You may only retrieve memberships for the authenticated user.")
     memberships = Membership.objects.select_related("leaderboard", "leaderboard__owner").annotate(score_count=Count("scores")).filter(user_id=user_id)
     serialiser = UserMembershipSerialiser(memberships, many=True)
     return Response(serialiser.data)
Example #20
0
 def create(self, request, patch_id, *args, **kwargs):
     p = get_object_or_404(Patch, id=patch_id)
     if not p.is_editable(request.user):
         raise PermissionDenied()
     request.patch = p
     return super(CheckListCreate, self).create(request, *args, **kwargs)
Example #21
0
class SubListCreateAPIView(SubListAPIView, ListCreateAPIView):
    # Base class for a sublist view that allows for creating subobjects and
    # attaching/detaching them from the parent.

    # In addition to SubListAPIView properties, subclasses may define (if the
    # sub_obj requires a foreign key to the parent):
    #   parent_key = 'field_on_model_referring_to_parent'

    def get_description_context(self):
        d = super(SubListCreateAPIView, self).get_description_context()
        d.update({
            'parent_key': getattr(self, 'parent_key', None),
        })
        return d

    def create(self, request, *args, **kwargs):
        # If the object ID was not specified, it probably doesn't exist in the
        # DB yet. We want to see if we can create it.  The URL may choose to
        # inject it's primary key into the object because we are posting to a
        # subcollection. Use all the normal access control mechanisms.

        # Make a copy of the data provided (since it's readonly) in order to
        # inject additional data.

        if hasattr(request.DATA, 'dict'):
            data = request.DATA.dict()
        else:
            data = request.DATA

        # add the parent key to the post data using the pk from the URL
        parent_key = getattr(self, 'parent_key', None)
        # logger.debug('SubListCreateAPIView.create: parent_key=%s', parent_key)
        if parent_key:
            data[parent_key] = self.kwargs['pk']
        # logger.debug('SubListCreateAPIView.create: data.parent_key=%s', data[parent_key])

        # attempt to deserialize the object
        try:
            serializer = self.serializer_class(data=data)
            if not serializer.is_valid():
                # logger.debug('SubListCreateAPIView.create: serializer failed validation')
                return Response(serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
        except Exception, e:
            # logger.debug('SubListCreateAPIView.create: serializer threw an error')
            return Response("serializer errors",
                            status=status.HTTP_400_BAD_REQUEST)

        # Verify we have permission to add the object as given.
        if not check_user_access(request.user, self.model, 'add',
                                 serializer.validated_data):
            # logger.debug('SubListCreateAPIView.create: permission denied user=%s model=%s action=add',
            #             request.user, self.model._meta.verbose_name)
            raise PermissionDenied()

        # save the object through the serializer, reload and return the saved
        # object deserialized

        try:
            self.pre_save(serializer.validated_data)
            obj = serializer.save()
            data = self.serializer_class(obj).data
        except IntegrityError, e:
            return Response("database integrity conflict",
                            status=status.HTTP_409_CONFLICT)
Example #22
0
 def check_push_permission(self, instance):
     if not instance.has_push_permission(self.request.user):
         raise PermissionDenied(
             _('You do not have "Push" permissions in the related repository'
               ))
Example #23
0
 def update(self, request, *args, **kwargs):
     customer = CustomerProfile.objects.get(pk=self.kwargs["pk"])
     if not request.user == customer.owner:
         raise PermissionDenied(
             "You have no permissions to edit this customer profile")
     return super().update(request, *args, **kwargs)
Example #24
0
 def _validate_user(self):
     if not self.request.user.is_staff:
         raise PermissionDenied()
Example #25
0
 def update(self, request, *args, **kwargs):
     image = Image.objects.get(pk=self.kwargs["pk"])
     if not request.user == image.owner:
         raise PermissionDenied(
             "You have no permissions to edit this photo")
     return super().update(request, *args, **kwargs)
Example #26
0
def collection_auth_check(request):
    ''' check permissions and 
        return a collection id (cid) if a collection exists and the user
        has permission to upload. If not, a permission denied is returned.
    '''
    if DISABLE_BUILDING:
        raise PermissionDenied(detail="Push is disabled.")

    auth = request.META.get('HTTP_AUTHORIZATION', None)

    # Load the body, which is json with variables
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    # Get variables
    tag = body.get('tag', 'latest')
    name = body.get('name')
    collection_name = format_collection_name(body.get('collection'))

    print(tag, name, collection_name, auth, body)

    # Authentication always required for push
    if auth is None:
        raise PermissionDenied(detail="Authentication Required")

    owner = get_request_user(auth)
    timestamp = generate_timestamp()
    payload = "push|%s|%s|%s|%s|" % (collection_name, timestamp, name, tag)

    # Validate Payload
    print(payload)
    if not validate_request(auth, payload, "push", timestamp):
        raise PermissionDenied(detail="Unauthorized")

    try:
        collection = Collection.objects.get(name=collection_name)

    except Collection.DoesNotExist:
        collection = None

    # Validate User Permissions, either for creating collection or adding
    # Here we have permission if:
    # 1- user collections are enabled with USER_COLLECTIONS
    # 2- the user is a superuser or staff
    # 3- the user is owner of a collection
    if not has_permission(auth, collection, pull_permission=False):
        raise PermissionDenied(detail="Unauthorized")

    # If the user cannot create a new collection
    if not owner.has_create_permission():
        raise PermissionDenied(detail="Unauthorized")

    # If we get here user has create permission, does collection exist?
    if collection is None:
        collection = Collection.objects.create(name=collection_name,
                                               secret=str(uuid.uuid4()))
        collection.save()
        collection.owners.add(owner)
        collection.save()

    # Return json response with collection id
    return JsonResponse({'cid': collection.id})
Example #27
0
 def destroy(self, request, *args, **kwargs):
     ep = Ep.objects.get(pk=self.kwargs["pk"])
     if not request.user == ep.owner:
         raise PermissionDenied("You can not delete this episode")
     return super().destroy(request, *args, **kwargs)
        if request.user:
            company = self.get_object()
            if company_position := CompanyPosition.objects.filter(
                    company=company, user=request.user).first():
                if company_position.can_edit:
                    return super().update(request, *args, **kwargs)
        raise PermissionDenied()

    def partial_update(self, request, *args, **kwargs):
        if request.user:
            company = self.get_object()
            if company_position := CompanyPosition.objects.filter(
                    company=company, user=request.user).first():
                if company_position.can_edit:
                    return super().partial_update(request, *args, **kwargs)
        raise PermissionDenied()

    @transaction.atomic()
    def destroy(self, request, *args, **kwargs):
        if request.user:
            company = self.get_object()
            if company_position := CompanyPosition.objects.filter(
                    company=company, user=request.user).first():
                if company_position.is_admin:
                    for job in company_position.company.jobs.all():
                        job.delete()
                    for position in company_position.company.positions.all():
                        position.delete()
                    return super().destroy(request, *args, **kwargs)
        raise PermissionDenied()
Example #29
0
 def is_image_owner(self, image, user):
     if image.owner.id != user.id:
         raise PermissionDenied()
Example #30
0
 def destroy(self, request, *args, **kwargs):
     raise PermissionDenied(self.message)