def test_authenticate_user_success(db: Session) -> None: faker = Faker() profile = faker.profile() email = profile.get("mail", None) username = profile.get("username", None) password = "******" user_in = schemas.UserCreate(username=username, email=email, password=SecretStr(password)) user = crud.user.create(db=db, obj_in=user_in) wrong_email = email + "xxx" authenticated_user = crud.user.authenticate(db, email=wrong_email, password=SecretStr(password)) assert not authenticated_user wrong_password = password + "xxx" authenticated_user = crud.user.authenticate( db, email=email, password=SecretStr(wrong_password)) assert not authenticated_user authenticated_user = crud.user.authenticate(db, email=email, password=SecretStr(password)) assert authenticated_user assert user.email == authenticated_user.email
def __init__(self, **data: Any): super().__init__(**data) if self.bearer_token is None: if self.consumer_key is None and self.consumer_secret is None: raise AttributeError( "consumer_key and consumer_secret required to generate bearer_token via Twitter" ) self.bearer_token = SecretStr(self.generate_bearer_token())
async def register_user(client: AsyncClient, email: EmailStr, password: SecretStr): path = "/auth/register" await client.post( path, json={ "email": email, "password": password.get_secret_value(), "confirm": password.get_secret_value(), "invitation": "", }, )
def test_create_user(db: Session) -> None: faker = Faker() profile = faker.profile() email = profile.get("mail", None) username = profile.get("username", None) password = "******" user_in = schemas.UserCreate(username=username, email=email, password=SecretStr(password)) user = crud.user.create(db=db, obj_in=user_in) assert user.email == email assert user.username == username assert hasattr(user, "hashed_password") assert security.verify_password(SecretStr(password), user.hashed_password)
class RabbitSettings(BaseCustomSettings): # host RABBIT_HOST: str = "rabbit" RABBIT_PORT: PortInt = 5672 # auth RABBIT_USER: str = "simcore" RABBIT_PASSWORD: SecretStr = SecretStr("simcore") # channels RABBIT_CHANNELS: Channels = { "log": "simcore.services.logs", "progress": "simcore.services.progress", "instrumentation": "simcore.services.instrumentation", "events": "simcore.services.events", } @cached_property def dsn(self) -> str: return RabbitDsn.build( scheme="amqp", user=self.RABBIT_USER, password=self.RABBIT_PASSWORD.get_secret_value(), host=self.RABBIT_HOST, port=f"{self.RABBIT_PORT}", )
class RabbitConfig(BaseSettings): # host host: str = "rabbit" port: PositiveInt = 5672 # auth user: str = "simcore" password: SecretStr = SecretStr("simcore") dsn: Optional[RabbitDsn] = None # channels channels: Dict[str, str] = { "log": "comp.backend.channels.log", "instrumentation": "comp.backend.channels.instrumentation", } @validator("dsn", pre=True) @classmethod def autofill_dsn(cls, v, values): if not v and all( key in values for key in cls.__fields__ if key not in ["dsn", "channels"] ): return RabbitDsn.build( scheme="amqp", user=values["user"], password=values["password"].get_secret_value(), host=values["host"], port=f"{values['port']}", ) return v class Config: env_prefix = "RABBIT_" extra = Extra.forbid
class RabbitConfig(BaseSettings): # host host: str = "rabbit" port: PositiveInt = 5672 # auth user: str = "simcore" password: SecretStr = SecretStr("simcore") # channels channels: Channels = { "log": "simcore.services.log", "progress": "simcore.services.progress", "instrumentation": "simcore.services.instrumentation", "events": "simcore.services.events", } @property def dsn(self) -> str: return RabbitDsn.build( scheme="amqp", user=self.user, password=self.password.get_secret_value(), host=self.host, port=f"{self.port}", ) class Config: env_prefix = "RABBIT_" extra = Extra.forbid
def main( endpoint: str, username: str, project_file: Path, project_name: Optional[str] = None, share_with_gid: int = EVERYONE_GROUP_ID, password: str = typer.Option( ..., prompt=True, confirmation_prompt=True, hide_input=True ), ) -> int: if project_name is None: project_name = project_file.name typer.secho( f"project {project_file} will be imported and named as {project_name}", fg=typer.colors.YELLOW, ) return asyncio.get_event_loop().run_until_complete( import_project_as_template( URL(endpoint), EmailStr(username), SecretStr(password), project_file, project_name, share_with_gid, ) )
class TwitterCredentials(BaseSettings): bearer_token: Optional[SecretStr] = Field(None, env="twitter_bearer_token") consumer_key: Optional[SecretStr] = Field(None, env="twitter_consumer_key") consumer_secret: Optional[SecretStr] = Field(None, env="twitter_consumer_secret") endpoint: str = Field("https://api.twitter.com/2/tweets/search/recent", env="twitter_endpoint") extra_headers_dict: Optional[Dict[str, Any]] = None def __init__(self, **data: Any): super().__init__(**data) if self.bearer_token is None: if self.consumer_key is None and self.consumer_secret is None: raise AttributeError( "consumer_key and consumer_secret required to generate bearer_token via Twitter" ) self.bearer_token = SecretStr(self.generate_bearer_token()) def get_twitter_credentials(self): if self.bearer_token is None: self.bearer_token = self.generate_bearer_token() return { "bearer_token": self.bearer_token.get_secret_value(), "endpoint": self.endpoint, "extra_headers_dict": self.extra_headers_dict, } # Copied from Twitter searchtweets-v2 lib def generate_bearer_token(self): """ Return the bearer token for a given pair of consumer key and secret values. """ data = [("grant_type", "client_credentials")] resp = requests.post( TWITTER_OAUTH_ENDPOINT, data=data, auth=( self.consumer_key.get_secret_value(), self.consumer_secret.get_secret_value(), ), ) logger.warning("Grabbing bearer token from OAUTH") if resp.status_code >= 400: logger.error(resp.text) resp.raise_for_status() return resp.json()["access_token"] class Config: arbitrary_types_allowed = True
async def login_user(client: AsyncClient, email: EmailStr, password: SecretStr): typer.secho( f"loging user {email}", ) path = "/auth/login" r = await client.post( path, json={"email": email, "password": password.get_secret_value()} ) r.raise_for_status() typer.secho( f"user {email} logged in", fg=typer.colors.YELLOW, )
def test_get_user_by(db: Session, search_by: str) -> None: faker = Faker() profile = faker.profile() email = profile.get("mail", None) username = profile.get("username", None) password = "******" user_in = schemas.UserCreate(username=username, email=email, password=SecretStr(password)) user = crud.user.create(db=db, obj_in=user_in) func_name = f"get_user_by_{search_by}" func = getattr(crud.user, func_name) user_2 = func(db, getattr(user, search_by)) assert user_2 assert user.email == user_2.email assert jsonable_encoder(user) == jsonable_encoder(user_2)
def __init__(self, **data: Any): super().__init__(**data) self.cred_info = self.cred_info or TwitterCredentials() if self.credential is not None: logger.warning("`credential` is deprecated; use `cred_info`") self.cred_info = self.credential if self.cred_info.bearer_token is None: if self.cred_info.consumer_key is None and self.cred_info.consumer_secret is None: raise AttributeError( "consumer_key and consumer_secret required to generate bearer_token via Twitter" ) self.cred_info.bearer_token = SecretStr( self.generate_bearer_token()) if self.max_tweets > 100: logger.warning( "Twitter API support max 100 tweets per call, hence resetting `max_tweets` to 100" ) self.max_tweets = 100
def test_should_commit_and_refresh_the_create_entity(self, faker, mocker): hashed_password = faker.sha1() db = mocker.MagicMock() created_user = UserFactory(password=SecretStr(hashed_password)) mocker.patch(f"{MODULE}.model.User", return_value=created_user) hash_password = mocker.patch( f"{MODULE}.security.password.hash_password", return_value=hashed_password, ) user_schema = schema.UserCreate(email=faker.email(), password=faker.word()) actual_user = CRUDUsers(model=model.User).create(db=db, schema=user_schema) assert actual_user == created_user hash_password.assert_called_once_with(created_user.password) db.add.assert_called_once_with(created_user) db.commit.assert_called_once() db.refresh.assert_called_once_with(created_user)
class MyEnum(Enum): foo = 'bar' snap = 'crackle' @pytest.mark.parametrize( 'input,output', [ (UUID('ebcdab58-6eb8-46fb-a190-d07a33e9eac8'), '"ebcdab58-6eb8-46fb-a190-d07a33e9eac8"'), (IPv4Address('192.168.0.1'), '"192.168.0.1"'), (Color('#000'), '"black"'), (Color((1, 12, 123)), '"#010c7b"'), (SecretStr('abcd'), '"**********"'), (SecretStr(''), '""'), (SecretBytes(b'xyz'), '"**********"'), (SecretBytes(b''), '""'), (IPv6Address('::1:0:1'), '"::1:0:1"'), (IPv4Interface('192.168.0.0/24'), '"192.168.0.0/24"'), (IPv6Interface('2001:db00::/120'), '"2001:db00::/120"'), (IPv4Network('192.168.0.0/24'), '"192.168.0.0/24"'), (IPv6Network('2001:db00::/120'), '"2001:db00::/120"'), (datetime.datetime(2032, 1, 1, 1, 1), '"2032-01-01T01:01:00"'), (datetime.datetime(2032, 1, 1, 1, 1, tzinfo=datetime.timezone.utc), '"2032-01-01T01:01:00+00:00"'), (datetime.datetime(2032, 1, 1), '"2032-01-01T00:00:00"'), (datetime.time(12, 34, 56), '"12:34:56"'), (datetime.timedelta(days=12, seconds=34, microseconds=56), '1036834.000056'),
def main(endpoint: str, username: str, password: str) -> int: return asyncio.get_event_loop().run_until_complete( create_user_with_password(URL(endpoint), EmailStr(username), SecretStr(password)))
def convert_to_app_config(app_settings: ApplicationSettings) -> Dict[str, Any]: """Maps current ApplicationSettings object into former trafaret-based config""" cfg = { "version": "1.0", "main": { "host": app_settings.WEBSERVER_SERVER_HOST, "port": app_settings.WEBSERVER_PORT, "log_level": f"{app_settings.WEBSERVER_LOG_LEVEL}", "testing": False, # TODO: deprecate! "studies_access_enabled": int(app_settings.WEBSERVER_STUDIES_DISPATCHER. STUDIES_ACCESS_ANONYMOUS_ALLOWED) if app_settings.WEBSERVER_STUDIES_DISPATCHER else 0, }, "tracing": { "enabled": 1 if app_settings.WEBSERVER_TRACING is not None else 0, # "zipkin_endpoint": f"{getattr(app_settings.WEBSERVER_TRACING, 'TRACING_ZIPKIN_ENDPOINT', None)}", }, "socketio": { "enabled": app_settings.WEBSERVER_SOCKETIO }, "director": { "enabled": app_settings.WEBSERVER_DIRECTOR is not None, "host": getattr(app_settings.WEBSERVER_DIRECTOR, "DIRECTOR_HOST", None), "port": getattr(app_settings.WEBSERVER_DIRECTOR, "DIRECTOR_PORT", None), "version": getattr(app_settings.WEBSERVER_DIRECTOR, "DIRECTOR_VTAG", None), }, "db": { "postgres": { "database": getattr(app_settings.WEBSERVER_DB, "POSTGRES_DB", None), "endpoint": f"{getattr(app_settings.WEBSERVER_DB, 'POSTGRES_HOST', None)}:{getattr(app_settings.WEBSERVER_DB, 'POSTGRES_PORT', None)}", "host": getattr(app_settings.WEBSERVER_DB, "POSTGRES_HOST", None), "maxsize": getattr(app_settings.WEBSERVER_DB, "POSTGRES_MAXSIZE", None), "minsize": getattr(app_settings.WEBSERVER_DB, "POSTGRES_MINSIZE", None), "password": getattr(app_settings.WEBSERVER_DB, "POSTGRES_PASSWORD", SecretStr("")).get_secret_value(), "port": getattr(app_settings.WEBSERVER_DB, "POSTGRES_PORT", None), "user": getattr(app_settings.WEBSERVER_DB, "POSTGRES_USER", None), }, "enabled": app_settings.WEBSERVER_DB is not None, }, "resource_manager": { "enabled": (app_settings.WEBSERVER_REDIS is not None and app_settings.WEBSERVER_RESOURCE_MANAGER is not None), "resource_deletion_timeout_seconds": getattr( app_settings.WEBSERVER_RESOURCE_MANAGER, "RESOURCE_MANAGER_RESOURCE_TTL_S", None, ), "garbage_collection_interval_seconds": getattr( app_settings.WEBSERVER_GARBAGE_COLLECTOR, "GARBAGE_COLLECTOR_INTERVAL_S", None, ), "redis": { "enabled": app_settings.WEBSERVER_REDIS is not None, "host": getattr(app_settings.WEBSERVER_REDIS, "REDIS_HOST", None), "port": getattr(app_settings.WEBSERVER_REDIS, "REDIS_PORT", None), }, }, # added to support legacy ---- "garbage_collector": { "enabled": app_settings.WEBSERVER_GARBAGE_COLLECTOR is not None }, "redis": { "enabled": app_settings.WEBSERVER_REDIS is not None }, # ----------------------------- "login": { "enabled": app_settings.WEBSERVER_LOGIN is not None, "registration_invitation_required": 1 if getattr( app_settings.WEBSERVER_LOGIN, "LOGIN_REGISTRATION_INVITATION_REQUIRED", None, ) else 0, "registration_confirmation_required": 1 if getattr( app_settings.WEBSERVER_LOGIN, "LOGIN_REGISTRATION_CONFIRMATION_REQUIRED", None, ) else 0, }, "smtp": { "sender": getattr(app_settings.WEBSERVER_EMAIL, "SMTP_SENDER", None), "host": getattr(app_settings.WEBSERVER_EMAIL, "SMTP_HOST", None), "port": getattr(app_settings.WEBSERVER_EMAIL, "SMTP_PORT", None), "tls": int(getattr(app_settings.WEBSERVER_EMAIL, "SMTP_TLS_ENABLED", 0)), "username": str(getattr(app_settings.WEBSERVER_EMAIL, "SMTP_USERNAME", None)), "password": str( getattr(app_settings.WEBSERVER_EMAIL, "SMTP_PASSWORD", None) and getattr(app_settings.WEBSERVER_EMAIL, "SMTP_PASSWORD", SecretStr("")).get_secret_value()), }, "storage": { "enabled": app_settings.WEBSERVER_STORAGE is not None, "host": getattr(app_settings.WEBSERVER_STORAGE, "STORAGE_HOST", None), "port": getattr(app_settings.WEBSERVER_STORAGE, "STORAGE_PORT", None), "version": getattr(app_settings.WEBSERVER_STORAGE, "STORAGE_VTAG", None), }, "catalog": { "enabled": app_settings.WEBSERVER_CATALOG is not None, "host": getattr(app_settings.WEBSERVER_CATALOG, "CATALOG_HOST", None), "port": getattr(app_settings.WEBSERVER_CATALOG, "CATALOG_PORT", None), "version": getattr(app_settings.WEBSERVER_CATALOG, "CATALOG_VTAG", None), }, "rest": { "version": app_settings.API_VTAG, "enabled": app_settings.WEBSERVER_REST is not None, }, "projects": { "enabled": app_settings.WEBSERVER_PROJECTS }, "session": { "secret_key": app_settings.WEBSERVER_SESSION.SESSION_SECRET_KEY.get_secret_value( ) }, "activity": { "enabled": app_settings.WEBSERVER_ACTIVITY is not None, "prometheus_host": getattr(app_settings.WEBSERVER_ACTIVITY, "origin", None), "prometheus_port": getattr(app_settings.WEBSERVER_ACTIVITY, "PROMETHEUS_PORT", None), "prometheus_api_version": getattr(app_settings.WEBSERVER_ACTIVITY, "PROMETHEUS_VTAG", None), }, "clusters": { "enabled": app_settings.WEBSERVER_CLUSTERS }, "computation": { "enabled": app_settings.is_enabled("WEBSERVER_COMPUTATION") }, "diagnostics": { "enabled": app_settings.is_enabled("WEBSERVER_DIAGNOSTICS") }, "director-v2": { "enabled": app_settings.is_enabled("WEBSERVER_DIRECTOR_V2") }, "exporter": { "enabled": app_settings.WEBSERVER_EXPORTER is not None }, "groups": { "enabled": app_settings.WEBSERVER_GROUPS }, "meta_modeling": { "enabled": app_settings.WEBSERVER_META_MODELING }, "products": { "enabled": app_settings.WEBSERVER_PRODUCTS }, "publications": { "enabled": app_settings.WEBSERVER_PUBLICATIONS }, "remote_debug": { "enabled": app_settings.WEBSERVER_REMOTE_DEBUG }, "security": { "enabled": True }, "scicrunch": { "enabled": app_settings.WEBSERVER_SCICRUNCH is not None }, "statics": { "enabled": app_settings.WEBSERVER_FRONTEND is not None and app_settings.WEBSERVER_STATICWEB is not None }, # NOTE app_settings.WEBSERVER_STUDIES_ACCESS_ENABLED did not apply "studies_dispatcher": { "enabled": app_settings.WEBSERVER_STUDIES_DISPATCHER is not None }, "tags": { "enabled": app_settings.WEBSERVER_TAGS }, "users": { "enabled": app_settings.WEBSERVER_USERS }, "version_control": { "enabled": app_settings.WEBSERVER_VERSION_CONTROL }, } return cfg