Example #1
0
    def create(self, request, *args, **kwargs):
        """
        Defines de POST method for register AccreditationAuthority

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})

        try:
            serializer.is_valid(raise_exception=True)
        except serializers.ValidationError as e:
            if "error" in e.args[0]:
                raise e

            raise handling_errors(e.args[0].items())

        try:
            validated_data = serializer.validated_data

            accreditation = contract_deployed("AccreditationAuthorityManager")
            accreditation.functions.getAccreditationAuthorityCount().call()
            tx_hash = accreditation.functions.insertAccreditationAuthority(
                Web3.toChecksumAddress(validated_data["owner"]),
                Web3.toBytes(text=validated_data["name"]),
                validated_data["id"]).transact(
                    {"from": validated_data["owner"]})
        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException("{}".format(vm_error["message"]), 1020)
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(
                    str(err)), 1021)

        user_created = User.objects.create(
            username=validated_data["email"].lower(),
            email=validated_data["email"].lower(),
            password=make_password(validated_data["password"].lower()),
            first_name=validated_data["name"],
            last_name="",
            is_active=True,
        )

        a_authority = AccreditationAuthority.objects.create(
            address=accreditation.functions.getAccreditationAuthority(
                Web3.toChecksumAddress(validated_data["owner"])).call(),
            owner=validated_data["owner"],
            user=user_created)

        Transaction.objects.create(hash=tx_hash,
                                   type=Transaction.INSERT,
                                   content_object=a_authority)

        token, created = Token.objects.get_or_create(user=user_created)

        return Response({"token": token.key})
Example #2
0
    def list(self, request, *args, **kwargs):
        try:
            ca = CertificationAuthority.objects.get(user=request.user)
            ca_instance = contract_deployed("CertificationAuthority", address=ca.address)

            certifiers_address = ca_instance.functions.getCertifierManager().call()
            certifiers_sc = contract_deployed("CertifierManager", address=certifiers_address)

            all_certifiers_sc = certifiers_sc.functions.getAllCertifiers().call()

            all_certifiers = list(map(
                lambda address:
                    contract_deployed(
                        "Certifier",
                        address=certifiers_sc.functions.getCertifier(address).call()
                    ).functions.getUser().call(),
                all_certifiers_sc
            ))
            print(all_certifiers)

        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException(
                "{}".format(vm_error["message"]),
                1020
            )
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(str(err)),
                1021
            )

        return Response([])
Example #3
0
    def create(self, request, *args, **kwargs):
        """
        Defines de POST method for register AccreditationAuthority

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})

        try:
            serializer.is_valid(raise_exception=True)
        except serializers.ValidationError as e:
            if "error" in e.args[0]:
                raise e

            raise handling_errors(e.args[0].items())

        try:
            validated_data = serializer.validated_data
            ca = CertificationAuthority.objects.get(user=request.user.id)

            certifier_from = Certifier.objects.get(
                owner=validated_data["from_owner"])
            certifier_to = Certifier.objects.get(
                owner=validated_data["to_owner"])
            certificate = contract_deployed(
                "Certificate", address=validated_data["certificate_address"])

            certifiers_dependencies_address = certificate.functions.getCertifierDependencies(
            ).call()
            certifiers_dependencies_sc = contract_deployed(
                "CertifierDependencyManager",
                address=certifiers_dependencies_address)
            tx_hash = certifiers_dependencies_sc.functions.insertCertifierDependency(
                validated_data["from_owner"],
                validated_data["to_owner"],
            ).transact({"from": ca.owner})

        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException("{}".format(vm_error["message"]), 1020)
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(
                    str(err)), 1021)

        certificate = Certificate.objects.get(
            address=validated_data["certificate_address"])

        Transaction.objects.create(hash=tx_hash,
                                   type=Transaction.UPDATE,
                                   content_object=certificate)

        return Response({"detail": "OK"})
Example #4
0
    def validate(self, attrs):
        """
        This function validates the data that comes in hand from the request
        to validate it in the serialziers.
        :param attrs:  attributes passed to the serialaizer
        :return: attrs
        """
        if not Web3.isChecksumAddress(attrs["certificate_address"]):
            raise CustomAPIException("Certificate is not a valid address.",
                                     1001)

        if not Certificate.objects.filter(
                address=attrs["certificate_address"]).exists():
            raise CustomAPIException("Certificate does not exist.", 1004)

        return attrs
Example #5
0
    def validate(self, attrs):
        """
        This function validates the data that comes in hand from the request
        to validate it in the serialziers.
        :param attrs:  attributes passed to the serialaizer
        :return: attrs
        """
        if not Web3.isChecksumAddress(attrs["owner"]):
            raise CustomAPIException("Owner is not a valid address.", 1001)

        if User.objects.filter(first_name__iexact=attrs["name"]).exists():
            raise CustomAPIException("Name Already in use.", 1002)

        if User.objects.filter(email__iexact=attrs["email"]).exists():
            raise CustomAPIException("Email Already in use.", 1002)

        if Recipient.objects.filter(owner=attrs["owner"]).exists():
            raise CustomAPIException("Owner already register.", 1003)

        return attrs
Example #6
0
    def list(self, request, *args, **kwargs):
        try:
            recipient = Recipient.objects.get(user=request.user.id)

            recipient_sc = contract_deployed("Recipient",
                                             address=recipient.address)
            certificates = contract_deployed(
                "CertificateManager",
                address=recipient_sc.functions.getCertificateManager().call(
                )).functions.getAllCertificates().call()

            certificates_all = []
            for address in certificates:
                certificate = contract_deployed("Certificate", address=address)
                info = certificate.functions.getInfo().call()
                dependencies = contract_deployed(
                    "CertifierDependencyManager",
                    address=certificate.functions.getCertifierDependencies(
                    ).call())
                sig_nonce = dependencies.functions.getAllSignerNonce().call()
                print(sig_nonce)
                certificates_all.append({
                    "title":
                    Web3.toText(info[0]).rstrip('\x00'),
                    "info":
                    Web3.toText(info[1]).rstrip('\x00'),
                    "address":
                    address,
                    "is_validated":
                    len(dependencies.functions.getAllSignerNonce().call()) > 0
                })

        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException("{}".format(vm_error["message"]), 1020)
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(
                    str(err)), 1021)

        return Response(certificates_all)
Example #7
0
    def post(self, request, *args, **kwargs):

        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        recipient = serializer.validated_data['email']

        try:
            Recipient.objects.get(user=recipient.user.id)
        except Exception:
            raise CustomAPIException("Recipient does not exist", 1100)

        token, created = Token.objects.get_or_create(user=recipient.user)

        return Response({
            'token': token.key
        })
Example #8
0
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']

        try:
            AccreditationAuthority.objects.get(user=user.id)
            # t = aa.transactions.first()
            # print(t.hash)
        except Exception:
            raise CustomAPIException("Accreditation Authority does not exist", 1100)

        token, created = Token.objects.get_or_create(user=user)

        return Response({
            'token': token.key
        })
Example #9
0
    def create(self, request, *args, **kwargs):
        """
        Defines de POST method for register AccreditationAuthority

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})

        try:
            serializer.is_valid(raise_exception=True)
        except serializers.ValidationError as e:
            if "error" in e.args[0]:
                raise e

            raise handling_errors(e.args[0].items())

        try:
            validated_data = serializer.validated_data
            certifier = Certifier.objects.get(user=request.user.id)
            certificate = contract_deployed(
                "Certificate", address=validated_data["certificate_address"])
            """
            Catch all contracts involved 
            """
            certifiers_dependencies_address = certificate.functions.getCertifierDependencies(
            ).call()
            certifiers_dependencies_sc = contract_deployed(
                "CertifierDependencyManager",
                address=certifiers_dependencies_address)

            signatures_address = certificate.functions.getSignatures().call()
            signatures_sc = contract_deployed("SignatureManager",
                                              address=signatures_address)
            """
            Make sign
            """
            nonce = w3.eth.getTransactionCount(certifier.owner)
            hash = w3.solidityKeccak(['address', 'uint256', 'bytes'], [
                certifier.owner, nonce,
                Web3.toHex(text=validated_data["params"])
            ])
            sign = w3.eth.sign(certifier.owner, hexstr=hash.hex())

            signature_hash = signatures_sc.functions.insertSignature(
                certifier.owner, nonce,
                Web3.toHex(text=validated_data["params"]),
                sign).transact({"from": certifier.owner})

            certifiers_dependencies_sc.functions.insertSignerNonce(
                certifier.owner, nonce).transact({"from": certifier.owner})

        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException("{}".format(vm_error["message"]), 1020)
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(
                    str(err)), 1021)

        certificate = Certificate.objects.get(
            address=validated_data["certificate_address"])

        Transaction.objects.create(hash=signature_hash,
                                   type=Transaction.UPDATE,
                                   content_object=certificate)

        return Response({"detail": "OK"})
Example #10
0
    def create(self, request, *args, **kwargs):
        """
        Defines de POST method for register AccreditationAuthority

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})

        try:
            serializer.is_valid(raise_exception=True)
        except serializers.ValidationError as e:
            if "error" in e.args[0]:
                raise e

            raise handling_errors(e.args[0].items())

        try:
            validated_data = serializer.validated_data

            recipient = Recipient.objects.get(
                address=validated_data["recipient_address"])
            certifier = Certifier.objects.get(user=request.user.id)
            recipient_sc = contract_deployed("Recipient",
                                             address=recipient.address)
            certifier_sc = contract_deployed("Certifier",
                                             address=certifier.address)
            certification_authority_sc = certifier_sc.functions.getCertificationAuthority(
            ).call()

            contract, tx_hash = contract_to_deploy(
                name="Certificate",
                from_address=certifier.owner,
                params=(
                    recipient_sc.address,
                    certifier_sc.address,
                    certification_authority_sc,
                    Web3.toBytes(text=validated_data["title"]),
                    Web3.toBytes(text=validated_data["description"]),
                ))
            tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)

            certificate_manager_address = recipient_sc.functions.getCertificateManager(
            ).call()

            certificate_manager = contract_deployed(
                "CertificateManager", address=certificate_manager_address)
            certificate_manager.functions.insertCertificate(
                tx_receipt.contractAddress).transact({"from": recipient.owner})

        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException("{}".format(vm_error["message"]), 1020)
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(
                    str(err)), 1021)

        certificate = Certificate.objects.create(
            title=validated_data["title"],
            address=tx_receipt.contractAddress,
            recipient=recipient,
        )
        certificate.certifiers.add(certifier)

        Transaction.objects.create(hash=tx_hash,
                                   type=Transaction.INSERT,
                                   content_object=certificate)

        return Response({"certificate_address": tx_receipt.contractAddress})
Example #11
0
    def create(self, request, *args, **kwargs):
        """
        Defines de POST method for register Recipient

        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        serializer = self.serializer_class(data=request.data,
                                           context={"request": request})

        try:
            serializer.is_valid(raise_exception=True)
        except serializers.ValidationError as e:
            if "error" in e.args[0]:
                raise e

            raise handling_errors(e.args[0].items())

        try:
            validated_data = serializer.validated_data
            ca = CertificationAuthority.objects.get(user=request.user)
            ca_instance = contract_deployed("CertificationAuthority",
                                            address=ca.address)
            recipient_manager_address = ca_instance.functions.getRecipientManager(
            ).call()
            recipient_manager = contract_deployed(
                "RecipientManager", address=recipient_manager_address)
            tx_hash = recipient_manager.functions.insertRecipient(
                ca.address, Web3.toChecksumAddress(validated_data["owner"]),
                Web3.toBytes(text=validated_data["name"]),
                Web3.toBytes(text=validated_data["email"]),
                Web3.toBytes(text=validated_data["id"]),
                validated_data["id_number"]).transact(
                    {"from": validated_data["owner"]})
        except ValueError as err:
            vm_error = json.loads(str(err).replace("\'", "\""))
            raise CustomAPIException("{}".format(vm_error["message"]), 1020)
        except Exception as err:
            raise CustomAPIException(
                "Undefined error, check connection to EVM: {}".format(
                    str(err)), 1021)

        user_created = User.objects.create(
            username=validated_data["email"].lower(),
            email=validated_data["email"].lower(),
            first_name=validated_data["name"],
            last_name="",
            is_active=True,
        )

        recipient = Recipient.objects.create(
            address=recipient_manager.functions.getRecipient(
                Web3.toChecksumAddress(validated_data["owner"])).call(),
            owner=validated_data["owner"],
            user=user_created)

        Transaction.objects.create(hash=tx_hash,
                                   type=Transaction.INSERT,
                                   content_object=recipient)

        token, created = Token.objects.get_or_create(user=user_created)

        return Response({"token": token.key})