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()
def count(self) -> Result[int, Error]: with self.session_scope() as session: users_count_model = session.query(self.UsersCountModel).first() if not users_count_model: return Success(0) return Success(users_count_model.count)
def get_config_logger( config_logger_dict: Dict) -> Result[ConfigLogger, Error]: if not config_logger_dict: return Success(ConfigLogger()) else: return Success(ConfigLogger.from_dict(config_logger_dict))
def test_should_be_the_same_a_result_with_true_success_with_a_success_class(): result = Result(success=True) success = Success() success_with_true = Success(True) assert result == success assert result == success_with_true assert result == isSuccess
def execute(self): if not self.setup_config: self.logger.log(WARNING, f"Empty config for setup") return Success() self.logger.log(INFO, f"setup: output: {self.setup_config.output}") for key, value in self.setup_config.deps.items(): self.logger.log(INFO, f"{key} : {value}") return Success()
def get_function_from_string(function_string: str) -> Result[Callable, Error]: if not function_string: return Success(None) try: mod_name, func_name = function_string.rsplit(".", 1) mod = importlib.import_module(mod_name) func = getattr(mod, func_name) return Success(func) except Exception as err: traceback.print_exc() print(err, file=sys.stderr) return isFailure
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))
def create_backend_token(self, user_id: str = None, verbose: bool = False) -> Result[str, AuthError]: """ Returns a BACKEND_TOKEN or BACKEND_TOKEN_WITH_USER depending of user_id given parameter. Both BACKEND_TOKEN and BACKEND_TOKEN_WITH_USER are used to secure global requests. 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 BACKEND_TOKEN or BACKEND_TOKEN_WITH_USER. Otherwise, it returns an OnboardingError. """ response = self._auth_client.create_backend_token(self._service_id, user_id, verbose=verbose) if response.status_code == 200: return Success(self.__get_token_from_response(response)) else: suffix = " (with user)" if user_id else "" return Failure( AuthError.from_response( operation=f"create_backend_token{suffix}", response=response))
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))
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 ) )
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))
def to_result(self) -> Result[Any, Error]: user_id = None if self == "None" else self if user_id is not None and len(user_id) > self.length: return Failure(InputExceedLengthLimitError(message=user_id)) else: return Success(user_id)
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))
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))
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))
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))
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))
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) )
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))
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))
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))
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))
def event_from_redis_message(message) -> Result[Event, Error]: try: json_data = message["data"].decode("utf-8") event = Event.from_json(json_data) return Success(event) except: # noqa E722 return isFailure(EventFromRedisMessageConversionError())
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))
def add_info_id(kwargs) -> Result[Tuple[str, InfoId], Error]: headers = kwargs.get("headers", {}) info_id = self.token_manager.execute(headers).unwrap_or_return() kwargs = dict(kwargs, info_id=info_id) return Success((kwargs, info_id))
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))
def run(self, name: str, dependency_config: DependencyConfig, logger: ILogger) -> Result: dependency_path = os.path.join(self.base_path, name) if not os.path.exists(dependency_path): os.makedirs(dependency_path) elif dependency_config.overwrite: logger.log( INFO, f"{self.__class__.__name__} - dependency {name} already exists. Overwriting..." ) else: logger.log( INFO, f"{self.__class__.__name__} - dependency {name} already exists. Skipping..." ) return Success() if dependency_config.auth_required: credentials_path = os.environ.get( dependency_config.credentials_env) if credentials_path is None or not os.path.exists( credentials_path): try: storage_client = storage.Client() except DefaultCredentialsError: return Failure( CrendentialsEnvError( dependency_config.credentials_env)) else: storage_client = storage.Client.from_service_account_json( credentials_path) else: storage_client = storage.Client() try: self.__download_bucket(storage_client, dependency_path, dependency_config.url) except NotFound: return Failure(BlobNotFoundError(dependency_config.url)) if dependency_config.unzip: try: unzip_file(dependency_path, dependency_config.url) except BadZipFile: return Failure(BadZipFileError(name)) return Success()
def retrieve(self, client_id: ClientId) -> Result[Client, Error]: with self.session_scope() as session: client_model = (session.query(self.ClientModel).filter( self.ClientModel.client_id == client_id.value).first()) self.fail_if_entity_not_exist(client_model, client_id).unwrap_or_return() client = Client.from_dict(client_model.__dict__) return Success(client)
def test_should_transform_a_success_result_encapsulated_value(): def transform(value): return f"{value} Meiga" result = Success("Hi") result.map(transform) assert result.value == "Hi Meiga"
def retrieve_all(self) -> Result[Events, Error]: with self.session_scope() as session: event_models = session.query(self.EventModel).all() events: Events = [] if event_models: for event_model in event_models: events.append(Event.from_json(event_model.data)) return Success(events)