Exemple #1
0
 def validate_token(self, token):
     print(token)
     user = User.verify_reset_password_token(token)
     print(User.verify_reset_password_token(token))
     if not user:
         raise ValidationError("Token is invalid")
Exemple #2
0
def validate_file_size(value):
    if value.size > 2000000:
        raise ValidationError('max file size: 2Mb')
Exemple #3
0
    def validate_amount(self, amount):
        valid_amounts = [100, 200, 300, 500, 800, 1000]
        if amount not in valid_amounts:
            raise ValidationError(f"{amount} er ikke en gyldig betalingspris")

        return amount
Exemple #4
0
    def to_internal_value_error(self, data):
        """ Returns both errors and valid data
        :returns: a couple: list of valid values
                            ValidationError with all errors
        """
        # Called 1 time for all the data list

        if fields.html.is_html_input(data):
            data = fields.html.parse_html_list(data)

        if not isinstance(data, list):
            message = self.error_messages['not_a_list'].format(
                input_type=type(data).__name__)
            raise ValidationError(
                {api_settings.NON_FIELD_ERRORS_KEY: [message]})

        detail = {
            'validation_errors': {},
            'no_address': 0,
            'duplicates': [],
            'results': []
        }
        unique_couples = set()
        messages = []

        cleaned_data = []
        for item in data:
            if not isinstance(item, dict):
                detail['no_address'] += 1
                continue
            # TODO: Must be 'recipient' instead of 'to' in v2
            if not item.get('to') or not item.get('message'):
                detail['no_address'] += 1
                continue

            # TODO: Must be 'recipient' instead of 'to' in v2
            unicity = (item['message'], item['to'])
            if unicity not in unique_couples:
                unique_couples.add(unicity)
            else:
                # TODO: Must be 'recipient' instead of 'to' in v2
                detail['duplicates'].append(item['to'])
                continue

            if item['message'] not in messages:
                if len(messages) > 0:
                    detail[api_settings.NON_FIELD_ERRORS_KEY] = [
                        'Every object must have same message'
                    ]
                    return [], detail
                messages.append(item['message'])

            cleaned_data.append(item)

        serializer = MailBulkSerializer(data=cleaned_data,
                                        many=True,
                                        context=self.context)

        if not serializer.is_valid():
            in_error, only_valid = [], []

            for error in serializer.errors:
                if error:
                    in_error.append(error['to'])
                    detail['validation_errors'][error['to']] = error['errors']

            for item in cleaned_data:
                if item['to'] not in in_error:
                    only_valid.append(item)

            serializer = MailBulkSerializer(data=only_valid,
                                            many=True,
                                            context=self.context)
            serializer.is_valid()

        cleaned_data = serializer.validated_data

        if cleaned_data:
            recipients = []
            results = []
            for item in cleaned_data:
                recipients.append(item['recipient'])

            recipients_to_remove = Mail.objects.filter(
                message=cleaned_data[0]['message'],
                recipient__in=recipients).values_list('recipient', flat=True)

            for item in cleaned_data:
                if item['recipient'] not in recipients_to_remove:
                    results.append(item)
                else:
                    detail['validation_errors'][item['recipient']] = [
                        _('This address is already attached to this message.')
                    ]

            cleaned_data = results

        return cleaned_data, detail
Exemple #5
0
    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise ValidationError(
                {"password": "******"})

        return attrs
Exemple #6
0
	def validate_device_id(self, value):
		# device ids are 64 bit unsigned values
		if value > UNSIGNED_64BIT_INT_MAX_VALUE:
			raise ValidationError("Device ID is out of range")
		return value
Exemple #7
0
def validate_is_alpha(value):
    if not bool(re.search('[a-zA-Z]', value)):
        raise ValidationError('Password should have at least one letter.')
Exemple #8
0
def string_validator(value):
    if not isinstance(value, str):
        raise ValidationError("Provided value is not a string type.")
    if value.isdigit():
        raise ValidationError("Provided value can not be a digit.")
 def validate_password(self, value):
     try:
         validate_password(value)
     except Exception as e:
         raise ValidationError(list(e.messages))
     return value
Exemple #10
0
def validate_currency(currency):
    # TODO:// wrap this function with daily cron job to update redis with the valid currencies list
    valid_currencies, _ = get_physical_currnencies()
    if currency not in valid_currencies:
        raise ValidationError(
            {"Currency": f"{currency} not a vaild currency!"})
Exemple #11
0
 def validate_username(self, value):
     username = value
     # username = self.cleaned_data.get('username')
     if User.objects.filter(username__icontains=username).exists():
         raise ValidationError("This username is taken")
     return username
Exemple #12
0
def validate_req_type(req_type):
    if req_type not in settings.ALLOWED_FUNCTIONS_LIST:
        raise ValidationError(
            {"Request type": f"{req_type} not a vaild request!"})
Exemple #13
0
    def validate_sources(sources):
        """Make sure the source is present."""
        if not sources:
            raise ValidationError(_(messages.SJ_REQ_SOURCES))

        return sources
Exemple #14
0
 def validate(self, data):
     if not set(data).issubset(VALID_EVENT_RESOURCES):
         raise ValidationError(u'Invalid event subscription: {}'.format(
             ', '.join(set(data).difference(VALID_EVENT_RESOURCES))))
Exemple #15
0
    def validate_credentials(credentials):
        """Make sure the credentials list is present."""
        if not credentials:
            raise ValidationError(_(messages.SOURCE_MIN_CREDS))

        return credentials
Exemple #16
0
    def validate(self, attrs):
        if attrs['addon'].premium_type in mkt.ADDON_FREES:
            raise ValidationError('App must be a premium app.')

        return attrs
Exemple #17
0
    def create(self, validated_data):
        """Create a source."""
        name = validated_data.get('name')
        check_for_existing_name(Source.objects, name,
                                _(messages.SOURCE_NAME_ALREADY_EXISTS % name))

        if 'source_type' not in validated_data:
            error = {'source_type': [_(messages.SOURCE_TYPE_REQ)]}
            raise ValidationError(error)
        source_type = validated_data.get('source_type')
        credentials = validated_data.pop('credentials')
        hosts_list = validated_data.pop('hosts', None)
        port = None
        if 'port' in validated_data:
            port = validated_data['port']

        options = validated_data.pop('options', None)

        if source_type == Source.NETWORK_SOURCE_TYPE:
            if credentials:
                for cred in credentials:
                    SourceSerializer.check_credential_type(source_type, cred)
            if port is None:
                validated_data['port'] = 22
        elif source_type == Source.VCENTER_SOURCE_TYPE:
            if port is None:
                validated_data['port'] = 443
            if hosts_list and len(hosts_list) != 1:
                error = {'hosts': [_(messages.VC_ONE_HOST)]}
                raise ValidationError(error)
            elif hosts_list and '[' in hosts_list[0]:
                error = {'hosts': [_(messages.VC_ONE_HOST)]}
                raise ValidationError(error)
            if credentials and len(credentials) > 1:
                error = {'credentials': [_(messages.VC_ONE_CRED)]}
                raise ValidationError(error)
            elif credentials and len(credentials) == 1:
                SourceSerializer.check_credential_type(source_type,
                                                       credentials[0])
        elif source_type == Source.SATELLITE_SOURCE_TYPE:
            if port is None:
                validated_data['port'] = 443
            if hosts_list and len(hosts_list) != 1:
                error = {'hosts': [_(messages.SAT_ONE_HOST)]}
                raise ValidationError(error)
            elif hosts_list and '[' in hosts_list[0]:
                error = {'hosts': [_(messages.VC_ONE_HOST)]}
                raise ValidationError(error)
            if credentials and len(credentials) > 1:
                error = {'credentials': [_(messages.SAT_ONE_CRED)]}
                raise ValidationError(error)
            elif credentials and len(credentials) == 1:
                SourceSerializer.check_credential_type(source_type,
                                                       credentials[0])

        source = Source.objects.create(**validated_data)

        if options:
            if source_type == Source.SATELLITE_SOURCE_TYPE:
                if options.get('ssl_cert_verify') is None:
                    options['ssl_cert_verify'] = True
            if (source_type == Source.VCENTER_SOURCE_TYPE
                    and options.get('ssl_cert_verify') is None):
                options['ssl_cert_verify'] = True
            if source_type == Source.NETWORK_SOURCE_TYPE and \
                    bool(options):
                invalid_options = ', '.join([key for key in options.keys()])
                error = {
                    'options': [
                        _(messages.NET_SSL_OPTIONS_NOT_ALLOWED %
                          invalid_options)
                    ]
                }
                raise ValidationError(error)

            options = SourceOptions.objects.create(**options)
            options.save()
            source.options = options
        elif not options and source_type == Source.SATELLITE_SOURCE_TYPE:
            options = SourceOptions()
            options.ssl_cert_verify = True
            options.save()
            source.options = options
        elif not options and source_type == Source.VCENTER_SOURCE_TYPE:
            options = SourceOptions()
            options.ssl_cert_verify = True
            options.save()
            source.options = options

        source.hosts = json.dumps(hosts_list)

        for credential in credentials:
            source.credentials.add(credential)

        source.save()
        return source
 def validate_with_items(self, value, loop_value='with_dict'):
     if value is None and self.custom_data.get(loop_value, None) is None:
         raise ValidationError(
             "with_items or with_dict field is required"
         )
     return value
Exemple #19
0
def validate_not_short(value):
    if len(value) < 6:
        raise ValidationError('Password should have at least 6 characters.')
 def validate(self, data):
     if 'options' not in data and 'items' not in data:
         raise ValidationError(
             'options field is required or items is required'
         )
     return super(MenuScreenSerializer, self).validate(data)
Exemple #21
0
def validate_is_numeric(value):
    if not bool(re.search('[0-9]', value)):
        raise ValidationError('Password should have at least one number.')
Exemple #22
0
    def update(self, instance, validated_data):
        """Update a source."""
        # If we ever add optional fields to Source, we need to
        # add logic here to clear them on full update even if they are
        # not supplied.
        name = validated_data.get('name')
        check_for_existing_name(Source.objects,
                                name,
                                _(messages.SOURCE_NAME_ALREADY_EXISTS % name),
                                search_id=instance.id)

        if 'source_type' in validated_data:
            error = {'source_type': [_(messages.SOURCE_TYPE_INV)]}
            raise ValidationError(error)
        source_type = instance.source_type
        credentials = validated_data.pop('credentials', None)
        hosts_list = validated_data.pop('hosts', None)
        options = validated_data.pop('options', None)

        if source_type == Source.NETWORK_SOURCE_TYPE:
            if credentials:
                for cred in credentials:
                    SourceSerializer.check_credential_type(source_type, cred)
        elif source_type == Source.VCENTER_SOURCE_TYPE:
            if hosts_list and len(hosts_list) != 1:
                error = {'hosts': [_(messages.VC_ONE_HOST)]}
                raise ValidationError(error)
            elif hosts_list and '[' in hosts_list[0]:
                error = {'hosts': [_(messages.VC_ONE_HOST)]}
                raise ValidationError(error)
            if credentials and len(credentials) > 1:
                error = {'credentials': [_(messages.VC_ONE_CRED)]}
                raise ValidationError(error)
            elif credentials and len(credentials) == 1:
                SourceSerializer.check_credential_type(source_type,
                                                       credentials[0])
        elif source_type == Source.SATELLITE_SOURCE_TYPE:
            if hosts_list and len(hosts_list) != 1:
                error = {'hosts': [_(messages.SAT_ONE_HOST)]}
                raise ValidationError(error)
            elif hosts_list and '[' in hosts_list[0]:
                error = {'hosts': [_(messages.VC_ONE_HOST)]}
                raise ValidationError(error)
            if credentials and len(credentials) > 1:
                error = {'credentials': [_(messages.SAT_ONE_CRED)]}
                raise ValidationError(error)
            elif credentials and len(credentials) == 1:
                SourceSerializer.check_credential_type(source_type,
                                                       credentials[0])

        for name, value in validated_data.items():
            setattr(instance, name, value)
        instance.save()

        # If hosts_list was not supplied and this is a full update,
        # then we should already have raised a ValidationError before
        # this point, so it's safe to use hosts_list as an indicator
        # of whether to replace the hosts.
        if hosts_list:
            hosts_data = json.dumps(hosts_list)
            instance.hosts = hosts_data

        # credentials is safe to use as a flag for the same reason as
        # hosts_data above.
        if credentials:
            instance.credentials.set(credentials)

        if options:
            if instance.options is None:
                if source_type == Source.NETWORK_SOURCE_TYPE and \
                        bool(options):
                    invalid_options = ', '.join(
                        [key for key in options.keys()])
                    error = {
                        'options': [
                            _(messages.NET_SSL_OPTIONS_NOT_ALLOWED %
                              invalid_options)
                        ]
                    }
                    raise ValidationError(error)

                options = SourceOptions.objects.create(**options)
                options.save()
                instance.options = options
            else:
                self.update_options(options, instance.options)

        instance.save()
        return instance
Exemple #23
0
 def validate_message(self, value):
     if value.status in [Message.SENDING, Message.SENT]:
         raise ValidationError(
             _("Cannot add this recipient to a "
               "sending or already sent message."))
     return value
Exemple #24
0
    def validate_name(name):
        """Validate the name of the Source."""
        if not isinstance(name, str) or not name.isprintable():
            raise ValidationError(_(messages.SOURCE_NAME_VALIDATION))

        return name
Exemple #25
0
def validate_extension(value):
    ext = os.path.splitext(value.name)[1]
    if not ext.lower() in ALLOWED_EXTS:
        raise ValidationError(f'not allowed file ext, allowed: {ALLOWED_EXTS}')
Exemple #26
0
    def validate_hosts(hosts):
        """Make sure the hosts list is present."""
        hosts_list = json.loads(hosts)
        if not isinstance(hosts_list, list):
            raise ValidationError(_(messages.SOURCE_HOST_MUST_BE_JSON_ARRAY))

        if not hosts_list:
            raise ValidationError(_(messages.SOURCE_HOSTS_CANNOT_BE_EMPTY))

        for host_value in hosts_list:
            if not isinstance(host_value, str):
                raise ValidationError(
                    _(messages.SOURCE_HOST_MUST_BE_JSON_ARRAY))

        # Regex for octet, CIDR bit range, and check
        # to see if it is like an IP/CIDR
        octet_regex = r'(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'
        bit_range = r'(3[0-2]|[1-2][0-9]|[0-9])'
        relaxed_ip_pattern = r'[0-9]*\.[0-9]*\.[0-9\[\]:]*\.[0-9\[\]:]*'
        relaxed_cidr_pattern = r'[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\/[0-9]*'
        greedy_subset = r'[0-9]*'
        range_subset = r'[0-9]*-[0-9]*'
        relaxed_invalid_ip_range = [
            r'{0}\.{0}\.{0}\.{0}-{0}\.{0}\.{0}\.{0}'.format(greedy_subset),
            r'{0}\.{0}\.{0}\.{1}'.format(greedy_subset, range_subset),
            r'{0}\.{0}\.{1}\.{0}'.format(greedy_subset, range_subset),
            r'{0}\.{1}\.{0}\.{0}'.format(greedy_subset, range_subset),
            r'{1}\.{0}\.{0}\.{0}'.format(greedy_subset, range_subset),
            r'{1}\.{1}\.{0}\.{0}'.format(greedy_subset, range_subset),
            r'{1}\.{0}\.{1}\.{0}'.format(greedy_subset, range_subset),
            r'{1}\.{0}\.{0}\.{1}'.format(greedy_subset, range_subset),
            r'{1}\.{1}\.{0}\.{1}'.format(
                greedy_subset, range_subset), r'{1}\.{0}\.{1}\.{1}'.format(
                    greedy_subset,
                    range_subset), r'{0}\.{0}\.{0}\.{0}'.format(range_subset),
            r'{0}\.{1}\.{0}\.{1}'.format(greedy_subset, range_subset),
            r'{0}\.{1}\.{1}\.{0}'.format(greedy_subset, range_subset)
        ]

        # type IP:          192.168.0.1
        # type CIDR:        192.168.0.0/16
        # type RANGE 1:     192.168.0.[1:15]
        # type RANGE 2:     192.168.[2:18].1
        # type RANGE 3:     192.168.[2:18].[4:46]
        ip_regex_list = [
            r'^{0}\.{0}\.{0}\.{0}$'.format(octet_regex),
            r'^{0}\.{0}\.{0}\.{0}\/{1}$'.format(octet_regex, bit_range),
            r'^{0}\.{0}\.{0}\.\[{0}:{0}\]$'.format(octet_regex),
            r'^{0}\.{0}\.\[{0}:{0}\]\.{0}$'.format(octet_regex),
            r'^{0}\.{0}\.\[{0}:{0}\]\.\[{0}:{0}\]$'.format(octet_regex)
        ]

        # type HOST:                abcd
        # type HOST NUMERIC RANGE:  abcd[2:4].foo.com
        # type HOST ALPHA RANGE:    abcd[a:f].foo.com
        host_regex_list = [
            r'[a-zA-Z0-9-\.]+',
            r'[a-zA-Z0-9-\.]*\[[0-9]+:[0-9]+\]*[a-zA-Z0-9-\.]*',
            r'[a-zA-Z0-9-\.]*\[[a-zA-Z]{1}:[a-zA-Z]{1}\][a-zA-Z0-9-\.]*'
        ]

        normalized_hosts = []
        host_errors = []
        for host_range in hosts_list:
            result = None
            ip_match = re.match(relaxed_ip_pattern, host_range)
            cidr_match = re.match(relaxed_cidr_pattern, host_range)
            invalid_ip_range_match = [
                re.match(invalid_ip_range, host_range)
                for invalid_ip_range in relaxed_invalid_ip_range
            ]
            is_likely_ip = ip_match and ip_match.end() == len(host_range)
            is_likely_cidr = cidr_match and cidr_match.end() == len(host_range)
            is_likely_invalid_ip_range = any(invalid_ip_range_match)

            if is_likely_invalid_ip_range:
                err_message = _(messages.NET_INVALID_RANGE_FORMAT %
                                (host_range, ))
                result = ValidationError(err_message)

            elif is_likely_ip or is_likely_cidr:
                # This is formatted like an IP or CIDR
                # (e.g. #.#.#.# or #.#.#.#/#)
                for reg in ip_regex_list:
                    match = re.match(reg, host_range)
                    if match and match.end() == len(host_range):
                        result = host_range
                        break

                if result is None or is_likely_cidr:
                    # Attempt to convert CIDR to ansible range
                    if is_likely_cidr:
                        try:
                            normalized_cidr = SourceSerializer \
                                .cidr_to_ansible(host_range)
                            result = normalized_cidr
                        except ValidationError as validate_error:
                            result = validate_error
                    else:
                        err_message = _(messages.NET_INVALID_RANGE_CIDR %
                                        (host_range, ))
                        result = ValidationError(err_message)
            else:
                # Possibly a host_range addr
                for reg in host_regex_list:
                    match = re.match(reg, host_range)
                    if match and match.end() == len(host_range):
                        result = host_range
                        break
                if result is None:
                    err_message = _(messages.NET_INVALID_HOST % (host_range, ))
                    result = ValidationError(err_message)

            if isinstance(result, ValidationError):
                host_errors.append(result)
            elif result is not None:
                normalized_hosts.append(result)
            else:
                # This is an unexpected case. Allow/log for analysis
                normalized_hosts.append(host_range)
                logging.warning('%s did not match a pattern or produce error',
                                host_range)
        if len(host_errors) is 0:
            return normalized_hosts
        else:
            error_message = [error.detail.pop() for error in host_errors]
            raise ValidationError(error_message)
Exemple #27
0
    def create(self, validated_data):
        """
        Overwrite create to handle the stripe charge before the relation is created.
        """
        request = self.context.get("request")
        user = request.user

        payment: Payment = validated_data.get("payment")
        payment_price: PaymentPrice = validated_data.get("payment_price")

        if not payment.is_user_allowed_to_pay(user):
            raise serializers.ValidationError(
                "Du har ikke tilgang til å betale for denne betalingen")
        """ Get stripe token and remove it from the data that from the create data """
        payment_method_id = validated_data.pop("payment_method_id")

        payment_relation: PaymentRelation = super().create({
            **validated_data, "status":
            status.PENDING
        })

        logger.info(
            f"Set up Stripe for payment:{payment.id}, user:{request.user.id}, "
            f"price: {payment_price.price} kr")
        try:
            """Validate and make the Intent with the Stripe payment method"""
            intent = stripe.PaymentIntent.create(
                payment_method=payment_method_id,
                amount=payment_price.price *
                100,  # Price is multiplied with 100 because the amount is in øre
                currency="nok",
                confirmation_method="manual",
                confirm=True,
                description=f"{payment.description()} - {request.user.email}",
                api_key=payment.stripe_private_key,
            )

            # If the payment needs more validation by Stripe or the bank
            if (intent.status == "requires_source_action"
                    and intent.next_action.type == "use_stripe_sdk"):
                payment_relation.status = status.PENDING
                payment_relation.payment_intent_secret = intent.client_secret

            elif intent.status == "succeeded":
                payment_relation.status = status.SUCCEEDED

            else:
                logger.error(
                    f"Payment intent returned an invalid status: {intent.status}"
                )
                raise ValidationError(
                    "Det skjedde noe galt under behandlingen av betalingen ")

            payment_relation.stripe_id = intent.id
            payment_relation.save()

            return payment_relation

        except stripe.error.CardError as err:
            error = err.json_body.get("error", {})
            logger.error(
                f"Stripe charge for {request.user} failed with card_error: {error}"
            )
            raise serializers.ValidationError(error)

        except stripe.error.StripeError as error:
            logger.error(
                f"An error occurred during the Stripe charge: {error}")
            raise serializers.ValidationError(error)

        return None
Exemple #28
0
    def cidr_to_ansible(ip_range):
        """Convert an IP address range from CIDR to Ansible notation.

        :param ip_range: the IP range, as a string
        :returns: the IP range, as an Ansible-formatted string
        :raises NotCIDRException: if ip_range doesn't look similar to CIDR
            notation. If it does look like CIDR but isn't quite right, print
            out error messages and exit.
        """
        # In the case of an input error, we want to distinguish between
        # strings that are "CIDR-like", so the user probably intended to
        # use CIDR and we should give them a CIDR error message, and not
        # at all CIDR-like, in which case we tell the caller to parse it a
        # different way.
        cidr_like = r'[0-9\.]*/[0-9]+'
        if not re.match(cidr_like, ip_range):
            err_msg = _(messages.NET_NO_CIDR_MATCH %
                        (ip_range, str(cidr_like)))
            raise ValidationError(err_msg)

        try:
            base_address, prefix_bits = ip_range.split('/')
        except ValueError:
            err_msg = _(messages.NET_CIDR_INVALID % (ip_range, ))
            raise ValidationError(err_msg)

        prefix_bits = int(prefix_bits)

        if prefix_bits < 0 or prefix_bits > 32:
            err_msg = _(messages.NET_CIDR_BIT_MASK % {
                'ip_range': ip_range,
                'prefix_bits': prefix_bits
            })
            raise ValidationError(err_msg)

        octet_strings = base_address.split('.')
        if len(octet_strings) != 4:
            err_msg = _(messages.NET_FOUR_OCTETS % (ip_range, ))
            raise ValidationError(err_msg)

        octets = [None] * 4
        for i in range(4):
            if not octet_strings[i]:
                err_msg = _(messages.NET_EMPTY_OCTET % (ip_range, ))
                raise ValidationError(err_msg)

            val = int(octet_strings[i])
            if val < 0 or val > 255:
                # pylint: disable=too-many-locals
                err_msg = _(messages.NET_CIDR_RANGE % {
                    'ip_range': ip_range,
                    'octet': val
                })
                raise ValidationError(err_msg)
            octets[i] = val

        ansible_out = [None] * 4
        for i in range(4):
            # "prefix_bits" is the number of high-order bits we want to
            # keep for the whole CIDR range. "mask" is the number of
            # low-order bits we want to mask off. Here prefix_bits is for
            # the whole IP address, but mask_bits is just for this octet.

            if prefix_bits <= i * 8:
                ansible_out[i] = '[0:255]'
            elif prefix_bits >= (i + 1) * 8:
                ansible_out[i] = str(octets[i])
            else:
                # The number of bits of this octet that we want to
                # preserve
                this_octet_bits = prefix_bits - 8 * i
                assert 0 < this_octet_bits < 8
                # mask is this_octet_bits 1's followed by (8 -
                # this_octet_bits) 0's.
                mask = -1 << (8 - this_octet_bits)

                lower_bound = octets[i] & mask
                upper_bound = lower_bound + ~mask
                ansible_out[i] = '[{0}:{1}]'.format(lower_bound, upper_bound)

        return '.'.join(ansible_out)
Exemple #29
0
    def create(self, validated_data):
        request = self.context.get("request")

        amount = validated_data.get("amount")
        payment_method_id = validated_data.pop("payment_method_id")

        logger.info(
            f"User: {request.user} attempting to add {amount} to saldo")

        transaction: PaymentTransaction = super().create({
            **validated_data, "status":
            status.PENDING
        })

        try:
            """Use Trikom key for additions to user saldo"""
            stripe_private_key = settings.STRIPE_PRIVATE_KEYS["trikom"]

            intent = stripe.PaymentIntent.create(
                payment_method=payment_method_id,
                amount=amount *
                100,  # Price is multiplied with 100 because the amount is in øre
                currency="nok",
                confirmation_method="manual",
                confirm=True,
                description=f"Saldo deposit - {request.user.email}",
                api_key=stripe_private_key,
            )

            # If the payment needs more validation by Stripe or the bank
            if (intent.status == "requires_source_action"
                    and intent.next_action.type == "use_stripe_sdk"):
                transaction.status = status.PENDING
                transaction.payment_intent_secret = intent.client_secret

            elif intent.status == "succeeded":
                transaction.status = status.SUCCEEDED

            else:
                logger.error(
                    f"Payment intent returned an invalid status: {intent.status}"
                )
                raise ValidationError(
                    "Det skjedde noe galt under behandlingen av betalingen ")

            transaction.stripe_id = intent.id
            transaction.save()

            return transaction

        except stripe.error.CardError as err:
            error = err.json_body.get("error", {})
            logger.error(
                f"Stripe charge for {request.user} failed with card_error: {error}"
            )
            raise ValidationError(error)

        except stripe.error.StripeError as error:
            logger.error(
                f"An error occurred during the Stripe charge: {error}")
            raise ValidationError(error)

        return None
Exemple #30
0
 def validate(self, data):
     try:
         validate_schema(data)
     except SchemaValidationError as e:
         raise ValidationError(e.message)