def auth_token( config: Config, logger: Logger, ) -> Generator[Dict[str, str], None, None]: retailer_repository = RetailerRepository(config, logger) auth_service = AuthService(config, logger, retailer_repository) reatailer_model = RetailerModel( full_name="Authenticated User", document="99899899899", email=EmailStr("*****@*****.**"), password="******", ) retailer_repository.insert_retailer(reatailer_model) retailer = retailer_repository.get_retailer_by_email("*****@*****.**") auth_token = auth_service.generate_access_token( {"sub": "*****@*****.**"}, expires_delta=timedelta( minutes=int(config.get_config("ACCESS_TOKEN_EXPIRE_MINUTES")) ), ) yield {"Authorization": f"Bearer {auth_token}"} if retailer: retailer_repository.delete_retailer(retailer.id)
def insert_default_user(database_connection): db = database_connection created_user = create_user( db, UserSchema(email=EmailStr("*****@*****.**"), username="******", password="******"), ) yield created_user
class Settings(BaseSettings): API_V1_STR: str = "/api/v1" SECRET_KEY: str = secrets.token_urlsafe(32) # 60 minutes * 24 hours * 8 days = 8 days ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 # BACKEND_CORS_ORIGINS is a JSON-formatted list of origins # e.g: '["http://localhost", "http://*****:*****@validator("BACKEND_CORS_ORIGINS", pre=True) def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]: if isinstance(v, str) and not v.startswith("["): return [i.strip() for i in v.split(",")] elif isinstance(v, (list, str)): return v raise ValueError(v) PROJECT_NAME: str EDGEDB_HOST: str EDGEDB_USER: str EDGEDB_PASSWORD: str EDGEDB_DB: str SMTP_TLS: bool = True SMTP_PORT: Optional[int] = None SMTP_HOST: Optional[str] = None SMTP_USER: Optional[str] = None SMTP_PASSWORD: Optional[str] = None EMAILS_FROM_EMAIL: Optional[EmailStr] = None EMAILS_FROM_NAME: Optional[str] = None EMAILS_SERVER_HOST: AnyHttpUrl @validator("EMAILS_FROM_NAME") def get_project_name(cls, v: Optional[str], values: Dict[str, Any]) -> str: if not v: return values["PROJECT_NAME"] return v EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 EMAIL_TEMPLATES_DIR: str = "app/email-templates/build" EMAILS_ENABLED: bool = False @validator("EMAILS_ENABLED", pre=True) def get_emails_enabled(cls, v: bool, values: Dict[str, Any]) -> bool: return bool( values.get("SMTP_HOST") and values.get("SMTP_PORT") and values.get("EMAILS_FROM_EMAIL") ) EMAIL_TEST_USER: EmailStr = EmailStr("*****@*****.**") FIRST_SUPERUSER: EmailStr FIRST_SUPERUSER_PASSWORD: str USERS_OPEN_REGISTRATION: bool = False class Config: case_sensitive = True env_file = ".env"
async def create_users(): # # Generate random email # with open('/usr/share/dict/cracklib-small', 'r') as w: # words = w.read().splitlines() # random_word = random.choice(words) # host = random.choice(['gmail', 'yahoo', 'amazon', 'yahoo', 'microsoft', 'google']) # tld = random.choice(['org', 'com', 'net', 'io', 'com.ph', 'co.uk']) # email = f'{random_word}@{host}.{tld}' # from app.auth import userdb async with in_transaction(): # User 1 userdata = UserCreate(email=EmailStr(VERIFIED_EMAIL_DEMO), password='******') create_user = get_create_user(userdb, UserDB) created_user = await create_user(userdata, safe=True) ret = created_user groups = await Group.filter(name__in=s.USER_GROUPS) user = await UserMod.get(pk=created_user.id) user.is_verified = True user.is_superuser = True await user.save() await user.groups.add(*groups) # Perms for User 1 ll = [] userperms = await Permission.filter(code__in=enchance_only_perms ).only('id') for perm in userperms: ll.append(UserPermissions(user=user, permission=perm, author=user)) await UserPermissions.bulk_create(ll) # Group or User 1 # await user.add_group('StaffGroup') # User 2 userdata = UserCreate(email=EmailStr(UNVERIFIED_EMAIL_DEMO), password='******') create_user = get_create_user(userdb, UserDB) created_user = await create_user(userdata, safe=True) groups = await Group.filter(name__in=s.USER_GROUPS) user = await UserMod.get(pk=created_user.id) await user.groups.add(*groups) return ret
async def send_html(file): html = await xls2html_tool(file) subject = f"{str(datetime.now().date())}行业动态" await send_mail([ EmailStr("*****@*****.**"), ], html, subject, email_type="html")
async def get_user(user_email: EmailStr) -> models.BaseUserDB: if not (user_email == EmailStr(user_email)): raise UserNotExists() user = await user_db.get_by_email(user_email) if user is None: raise UserNotExists() return user
class LetoAtreides: ID: int EMAIL = EmailStr('*****@*****.**') FIRST_NAME = 'Leto' LAST_NAME = 'Atreides' PASSWORD = '******' HASHED_PASSWORD, SALT = hash_password(PASSWORD) AGE = 51 CITY = 'Arrakis' GENDER = 'MALE'
class ShaddamIV: ID: int EMAIL = EmailStr('*****@*****.**') FIRST_NAME = 'Shaddam' LAST_NAME = 'IV' PASSWORD = '******' HASHED_PASSWORD, SALT = hash_password(PASSWORD) AGE = 68 CITY = None GENDER = None
def __init__(self, items: Iterable[Section] = None): super().__init__(items) self.name: str = "" self.label: str = "" self.email: EmailStr = EmailStr("") self.location: Location = Location.construct() self.phone: Optional[str] = "" self.picture: Optional[str] = "" self.summary: Optional[str] = "" self.website: Optional[HttpUrl] = None
class VladimirHarconnen: ID: int EMAIL = EmailStr('*****@*****.**') FIRST_NAME = 'Vladimir' LAST_NAME = 'Harkonnen' PASSWORD = '******' HASHED_PASSWORD, SALT = hash_password(PASSWORD) AGE = 83 CITY = 'Arrakis' GENDER = 'MALE'
def test_create_user(db: Session) -> None: email = EmailStr("*****@*****.**") password = "******" first_name = "Valon" last_name = "diqka" user_in = UserCreate(first_name=first_name, last_name=last_name, email=email, password=password) user = user_service.create(user_create=user_in, db=db) assert user.email == email assert user.last_name == last_name
def register(email: str, username: str, password: str): url: str = get_url(url=f"/user/register") try: body = UserRegisterBodyModel( username=username, email=EmailStr(email), password=password, ) response = httpx.post(url=url, json=body.dict()) response_handler(response=response, return_model=UserRegisterResponseModel) except ValidationError: print_error("Check your inputs")
class UserSchema(BaseModel): # _id: ObjectId name: str = Field(...) email: str = EmailStr(...) password: str = Field(...) class Config: schema_extra = { "example ": { "name": "タロー", "email": "*****@*****.**", "password": "******" } }
def test_get_user(database_connection): db = database_connection user_password = "******" created_user = create_user( db, UserSchema( email=EmailStr("*****@*****.**"), username="******", password=user_password ), ) users_in_db = get_users(db) assert len(users_in_db) == 1 for u in users_in_db: assert u.email == created_user.email assert u.username == created_user.username assert verify_password(user_password, u.password)
async def send_internal(subject: str, recipients: List[str], body: str, subtype: Optional[str] = None, file_attachments: Optional[List[str]] = None): if file_attachments is None: file_attachments = [] message = MessageSchema( subject=subject, recipients=[EmailStr(recipient) for recipient in recipients], body=body, subtype=subtype, attachments=[UploadFile(file_attachment) for file_attachment in file_attachments]) return await send_internal_internal(message)
def create(self, name: str, email: str) -> None: """Creates a new rezume.yml file based on the template rezume.""" template_path = InitCommand.get_template_path() if not template_path.exists(): typer.secho("\nrezume template file not found.\n", fg=typer.colors.RED) self.exit() try: rezume = Rezume() rezume.load(template_path) rezume.name = name rezume.email = EmailStr(email) rezume.save(self.filename, overwrite=True, exclude_none=True) typer.secho( f"\nYour {self.filename.name} file has been created!\n", fg=typer.colors.GREEN, ) except RezumeError as ex: typer.secho(f"\nerror: {ex}") self.exit()
def validate_email(cls, v: Any) -> Optional[EmailStr]: if not v: return None return EmailStr(v)
current_user: UserInDB = Depends(get_current_active_user)): return current_user template = """ <html> <body> <h3>this mail is from kako app</h3> <p>Complete your registration</p> <p><b>your activation code is: {}</b></p> <p>enter this code in kako app.</p> </body> </html> """ conf = ConnectionConfig(MAIL_USERNAME=EmailStr("*****@*****.**"), MAIL_PASSWORD="******", MAIL_PORT=587, MAIL_SERVER="smtp.gmail.com", MAIL_TLS=True, MAIL_SSL=False) async def send_activation_email(user: UserInDB): email_template = template.format(str(user.activation_code)) print(email_template) message = MessageSchema(subject="Kako app - activation code", recipients=[user.email], body=email_template, subtype="html")
row = await conn[mongo_db][mongo_collection].find_one({"email": api_email}) if row: print(f"User {api_email} already exists.") else: user: BaseUserCreate = BaseUserCreate(email=api_email) api_key = await create_api_user(conn, user, is_superuser=True) return api_key if __name__ == "__main__": if len(sys.argv) == 1: sys.exit( "No email id provided. Provide an email to create your first user") email = EmailStr(sys.argv[1]) db = AsyncIOMotorClient(mongo_url, maxPoolSize=mongo_max_connections, minPoolSize=mongo_min_connections) collections = db[mongo_db][mongo_collection] api_key = loop.run_until_complete(first_user(db, email)) if not api_key: print("Creating of user unsuccessful.") if SG_API and api_key: message = Mail( from_email=FROM_EMAIL, to_emails=str(email), subject='Your API Key',
def main( endpoint: str, username: str, password: str, project_id: Optional[str] = None ) -> int: return asyncio.get_event_loop().run_until_complete( clean(URL(endpoint), EmailStr(username), SecretStr(password), project_id) )
class InputSchema(BaseModel): email = EmailStr()
def test_email_str(): class Model(BaseModel): v: EmailStr assert Model(v=EmailStr('*****@*****.**')).v == '*****@*****.**' assert Model(v='*****@*****.**').v == '*****@*****.**'
from settings.grabbers import FeedlyGrabberSettings from settings.notification_channels import \ SendPulseNotificationChannelSettings zzr_settings = RESTAdapterSettings( client_id=os.environ["ZZR_CLIENT_ID"], client_secret=os.environ["ZZR_CLIENT_SECRET"], token_url=parse_obj_as(HttpUrl, os.environ["ZZR_TOKEN_URL"]), base_url=parse_obj_as(HttpUrl, os.environ["ZZR_BASE_URL"]), authorization_url=parse_obj_as(HttpUrl, os.environ["ZZR_AUTHORIZATION_URL"]), ) feedly_settings = FeedlyGrabberSettings( refresh_token=str(os.environ.get("FEEDLY_REFRESH_TOKEN")), returned_posts_count=int(os.environ["FEEDLY_RETURNED_POSTS_COUNT"]), ) emails = [ EmailStr(email) for email in os.environ["SENDPULSE_NOTIFICATION_EMAILS"].split(",") ] sendpulse_settings = SendPulseNotificationChannelSettings( emails=emails, client_id=os.environ["SENDPULSE_CLIENT_ID"], client_secret=os.environ["SENDPULSE_CLIENT_SECRET"], token_url=parse_obj_as(HttpUrl, os.environ["SENDPULSE_TOKEN_URL"]), base_url=parse_obj_as(HttpUrl, os.environ["SENDPULSE_BASE_URL"]), )