Ejemplo n.º 1
0
    def run(self, name: str, dependency_config: DependencyConfig,
            logger: ILogger) -> Result:
        dependency_path = os.path.join(self.base_path, name)
        if os.path.exists(dependency_path):
            logger.log(
                INFO,
                f"{self.__class__.__name__} - dependency {name} already exists"
            )
            return Success()
        os.makedirs(dependency_path, exist_ok=True)

        if not dependency_config.auth_required:
            auth = None
        else:
            credentials_var = os.environ.get(dependency_config.credentials_env)
            if credentials_var is None:
                return Failure(
                    CrendentialsEnvError(dependency_config.credentials_env))
            username, password = credentials_var.split(":")
            auth = HTTPBasicAuth(username, password)

        self.__download_file(dependency_path, dependency_config.url, auth)

        if dependency_config.unzip:
            try:
                unzip_file(dependency_path, dependency_config.url)
            except BadZipFile:
                return Failure(BadZipFileError(name))

        return Success()
Ejemplo n.º 2
0
def test_should_be_the_same_a_result_with_an_error_failure_with_a_failure_class(
):

    result = Result(failure=Error())
    failure = Failure()
    failure_with_error = Failure(Error())

    assert result == failure
    assert result == failure_with_error
    assert result == isFailure
Ejemplo n.º 3
0
 def from_filename(filename: str) -> Result[Any, Error]:
     if not os.path.isfile(filename):
         return Failure(ConfigFileNotFoundError(filename))
     try:
         with open(filename) as file:
             petisco_dict = yaml.load(file, Loader=yaml.FullLoader)
             config_event = ConfigEvents.from_dict(petisco_dict)
             return Success(config_event)
     except (ParserError, ScannerError) as e:
         message = f"Error loading {filename} file: {repr(e.__class__)} {e} | {traceback.format_exc()}"
         return Failure(ConfigFileNotValidError(message))
Ejemplo n.º 4
0
    def to_result(self) -> Result[Any, Error]:
        name = None if self == "None" else self

        if name is not None:
            if len(self) > self.length_limit:
                return Failure(InputExceedLengthLimitError(message=name))
            else:
                if not re.search(r"^[a-zA-Z]*(([',. -][a-zA-Z ])?[a-zA-Z]*)*$",
                                 name):
                    return Failure(GivenInputIsNotValidError(message=name))
        return Success(name)
Ejemplo n.º 5
0
    def get_commands(self, action) -> Result[List[str], Error]:
        if action == "install":
            if not self.config.install:
                return Failure(EmptyConfigError())
            commands = self.config.install.run
        else:
            step = self.config.steps.get(action)
            if not step:
                return Failure(EmptyConfigError())
            commands = step.run

        return Success(commands)
Ejemplo n.º 6
0
    def to_result(self) -> Result[Any, Error]:
        client_id = None if self == "None" else self

        if client_id is not None:
            if len(client_id) > self.length:
                return Failure(InputExceedLengthLimitError(message=client_id))
            else:
                if not re.search(r"^[a-zA-Z]*(([',. -][a-zA-Z ])?[a-zA-Z]*)*$",
                                 client_id):
                    return Failure(
                        GivenInputIsNotValidError(message=client_id))
        return Success(client_id)
Ejemplo n.º 7
0
def get_config(filename: str = r"lume.yml") -> Result[Config, Error]:
    if not os.path.isfile(filename):
        return Failure(ConfigFileNotFoundError(filename))

    try:
        with open(filename) as file:
            lume_dict = yaml.load(file, Loader=yaml.FullLoader)
            config = Config(lume_dict)
            return Success(config)
    except ParserError as e:
        message = f"Error loading {filename} file: {repr(e.__class__)} {e} | {traceback.format_exc()}"
        return Failure(ConfigFileNotValidError(message))
Ejemplo n.º 8
0
 def from_filename(filename: str) -> Result[Any, Error]:
     if not os.path.isfile(filename):
         return Failure(ConfigFileNotFoundError(filename))
     try:
         petisco_yml_folder = os.path.dirname(filename)
         with open(filename) as file:
             petisco_dict = yaml.load(file, Loader=yaml.FullLoader)
             petisco_dict["petisco_yml_folder"] = petisco_yml_folder
             config = Config.from_dict(petisco_dict).unwrap_or_return()
             return Success(config)
     except (ParserError, ScannerError) as e:
         message = f"Error loading {filename} file: {repr(e.__class__)} {e} | {traceback.format_exc()}"
         return Failure(ConfigFileNotValidError(message))
Ejemplo n.º 9
0
    def create_certificate(
            self,
            user_id: str,
            template_name: str = "default",
            verbose: bool = False) -> Result[Dict, OnboardingError]:
        """
        This call is used to create a Certificate (Signed PDF Report) of the onboarding process for a specific user.
        It returns a identifier (certificate_id) as a reference of created resource.
        This resource contains all evidence defined in the template.


        Parameters
        ----------
        user_id
            User identifier
        template_name
            'default' (only available)
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a str with a pdf_report_id.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.create_certificate(
            user_id=user_id, template_name=template_name, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["certificate_id"])
        else:
            return Failure(
                OnboardingError.from_response(operation="create_certificate",
                                              response=response))
Ejemplo n.º 10
0
    def create_report(self,
                      user_id: str,
                      verbose: bool = False) -> Result[Dict, OnboardingError]:
        """

        This call is used to get the report of the onboarding process for a specific user.
        It returns information on all evidence that has been added and analyzed for that user,
        including documents and facial verifications.


        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the generated report.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.create_report(user_id=user_id,
                                                        verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["report"])
        else:
            return Failure(
                OnboardingError.from_response(operation="create_report",
                                              response=response))
Ejemplo n.º 11
0
    def document_properties(
            self,
            user_id: str,
            document_id: str,
            verbose: bool = False) -> Result[str, OnboardingError]:
        """

        Returns the properties of a previously added document, such as face, MRZ or NFC availability

        Parameters
        ----------
        user_id
            User identifier

        document_id
            Document identifier

        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns dict with document properties.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.document_properties(
            user_id=user_id, document_id=document_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json())
        else:
            return Failure(
                OnboardingError.from_response(operation="document_properties",
                                              response=response))
Ejemplo n.º 12
0
    def void_document(self,
                      user_id: str,
                      document_id: str,
                      verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        Mark a document as invalid.


        Parameters
        ----------
        user_id
            User identifier
        document_id
            Document identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.void_document(
            user_id=user_id, document_id=document_id, verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="void_document",
                                              response=response))
Ejemplo n.º 13
0
    def supported_documents(
            self,
            user_id: str,
            verbose: bool = False) -> Result[Dict[str, str], OnboardingError]:
        """
        This method is used to obtain a hierarchical-ordered dict with the information of the documents supported by the API.

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns dict with supported document.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.supported_documents(user_id=user_id,
                                                              verbose=verbose)
        if response.status_code == 200:
            return Success(response.json())
        else:
            return Failure(
                OnboardingError.from_response(operation="supported_documents",
                                              response=response))
Ejemplo n.º 14
0
    def void_selfie(self,
                    user_id: str,
                    verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        This call is used to void the video of the user's face to the onboarding service.
        This will NOT erase the biometric face profile.

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.void_selfie(user_id=user_id,
                                                      verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="void_selfie",
                                              response=response))
Ejemplo n.º 15
0
    def create_user_token(self,
                          user_id: str,
                          verbose: bool = False) -> Result[str, AuthError]:
        """
        Returns a USER_TOKEN.
        The USER_TOKEN is used to secure requests made by the users on their mobile devices or web clients.


        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns USER_TOKEN.
            Otherwise, it returns an OnboardingError.
        """
        response = self._auth_client.create_user_token(self._service_id,
                                                       user_id,
                                                       verbose=verbose)

        if response.status_code == 200:
            return Success(self.__get_token_from_response(response))
        else:
            return Failure(
                AuthError.from_response(operation="create_user_token",
                                        response=response))
Ejemplo n.º 16
0
    def delete_user(self,
                    user_id: str,
                    verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        Delete all the information of a user

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.delete_user(user_id=user_id,
                                                      verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="delete_user",
                                              response=response))
Ejemplo n.º 17
0
    def get_authentication(
            self,
            user_id: str,
            authentication_id: str,
            verbose: bool = False) -> Result[Dict, OnboardingError]:
        """

        Returns the result of a authentication given a authentication_id

        Parameters
        ----------
        user_id
            User identifier
        authentication_id
            Authentication identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the information of one authentication.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_authentication(
            user_id=user_id,
            authentication_id=authentication_id,
            verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["authentication"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_authentication",
                                              response=response))
Ejemplo n.º 18
0
    def authenticate_user(
            self,
            user_id: str,
            media_data: bytes,
            verbose: bool = False) -> Result[str, OnboardingError]:
        """

        Authenticate a previously registered User against a given media to verify the identity

        Parameters
        ----------
        user_id
            User identifier
        media_data
            Binary media data.
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a authentication_id.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.authenticate_user(
            user_id=user_id, media_data=media_data, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["authentication_id"])
        else:
            return Failure(
                OnboardingError.from_response(operation="authenticate_user",
                                              response=response))
Ejemplo n.º 19
0
    def retrieve_certificate(
            self,
            user_id: str,
            certificate_id: str,
            verbose: bool = False) -> Result[bytes, OnboardingError]:
        """

        Returns the binary data of an existent pdf report

        Parameters
        ----------
        user_id
            User identifier
        certificate_id
           Certificate Unique Identifier. You can obtain it using create_certificate method.
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a binary pdf (bytes).
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.retrieve_certificate(
            user_id=user_id, certificate_id=certificate_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.content)
        else:
            return Failure(
                OnboardingError.from_response(operation="retrieve_certificate",
                                              response=response))
Ejemplo n.º 20
0
    def delete_user(
        self, email: str, verbose: bool = False
    ) -> Result[bool, SandboxError]:
        """

        Delete all the information of a Sandbox User. Including the link with Onboarding user.
        Note this command will execute also Onboarding User Deletion.

        Parameters
        ----------
        email
            User's email
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an SandboxError.
        """
        response = self.sandbox_client.delete_user(email=email, verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                SandboxError.from_response(operation="delete_user", response=response)
            )
Ejemplo n.º 21
0
    def get_user_token(
        self, email: str, verbose: bool = False
    ) -> Result[str, SandboxError]:
        """

        Returns user token linked to Onboarding User managed by the Sandbox Service

        Parameters
        ----------
        email
            User's email
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns list of string with already created user_ids.
            Otherwise, it returns an SandboxError.
        """
        response = self.sandbox_client.get_user_token(email=email, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["user_token"])
        else:
            return Failure(
                SandboxError.from_response(
                    operation="get_user_token", response=response
                )
            )
Ejemplo n.º 22
0
    def get_user(self, email: str, verbose: bool = False) -> Result[Dict, SandboxError]:
        """

        Returns User Status of a Sandbox user

        Parameters
        ----------
        email
            User's email
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the status info.
            Otherwise, it returns an SandboxError.
        """
        response = self.sandbox_client.get_user(email=email, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json())
        else:
            return Failure(
                SandboxError.from_response(operation="get_user", response=response)
            )
Ejemplo n.º 23
0
    def retrieve_certificates(
            self,
            user_id: str,
            verbose: bool = False) -> Result[List, OnboardingError]:
        """

        Returns summary info for created certificates

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a list of dictionaries.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.retrieve_certificates(
            user_id=user_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["certificates"])
        else:
            return Failure(
                OnboardingError.from_response(
                    operation="retrieve_certificates", response=response))
Ejemplo n.º 24
0
    def get_user_status(
            self,
            user_id: str,
            verbose: bool = False) -> Result[Dict, OnboardingError]:
        """

        Returns User status to be used as feedback from the onboarding process

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the status info.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_user_status(user_id=user_id,
                                                          verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["user"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_user_status",
                                              response=response))
Ejemplo n.º 25
0
    def get_authentications_ids(
            self,
            user_id: str,
            verbose: bool = False) -> Result[List[str], OnboardingError]:
        """

        Returns all authentications ids you have performed for a User, sorted by creation date in descending order.

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a List of string with all the authentication_ids.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_authentications_ids(
            user_id=user_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["authentication_ids"])
        else:
            return Failure(
                OnboardingError.from_response(
                    operation="get_authentications_ids", response=response))
Ejemplo n.º 26
0
    def get_users(self,
                  verbose: bool = False) -> Result[List[str], OnboardingError]:
        """

        Returns all users you have created, sorted by creation date in descending order.

        Parameters
        ----------
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns list of string with already created user_ids.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_users()

        if response.status_code == 200:
            return Success(response.json()["users"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_users",
                                              response=response))
Ejemplo n.º 27
0
    def retrieve_media(
            self,
            user_id: str,
            media_id: str,
            verbose: bool = False) -> Result[bytes, OnboardingError]:
        """

        Returns the binary data of a media resource

        Parameters
        ----------
        user_id
            User identifier
        media_id
            Identifier obtained, for example from the report
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a binary image (bytes).
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.retrieve_media(user_id=user_id,
                                                         media_id=media_id,
                                                         verbose=verbose)

        if response.status_code == 200:
            return Success(response.content)
        else:
            return Failure(
                OnboardingError.from_response(operation="retrieve_media",
                                              response=response))
Ejemplo n.º 28
0
    def get_users_stats(self,
                        verbose: bool = False
                        ) -> Result[Dict, OnboardingError]:
        """

        Returns statistics about users in the Onboarding platform.

        Parameters
        ----------
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a dict with users information
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_users_stats(verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["stats"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_users_stats",
                                              response=response))
Ejemplo n.º 29
0
 def exists(self, user_id: UserId) -> Result[bool, Error]:
     with self.session_scope() as session:
         user = (session.query(self.UserModel).filter(
             self.UserModel.user_id == user_id.value).first())
         if user:
             return isSuccess
         return Failure(UserNotFoundError(user_id))
Ejemplo n.º 30
0
    def add_selfie(self,
                   user_id: str,
                   media_data: bytes,
                   verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        This call is used to upload for the first time the video of the user's face to the onboarding service.
        This video will be used to extract the biometric face profile.

        Parameters
        ----------
        user_id
            User identifier
        media_data
            Binary media data.
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.add_selfie(user_id=user_id,
                                                     media_data=media_data,
                                                     verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="add_selfie",
                                              response=response))