Ejemplo n.º 1
0
def send_invitation(invitation: InvitationParams,
                    background_task: BackgroundTasks):
    """
    This function sends the recipient an invitation
    to his email address in the format HTML.
    :param invitation: InvitationParams, invitation parameters
    :param background_task: BackgroundTasks
    :return: json response message,
    error message if the entered email address is incorrect,
    confirmation message if the invitation was successfully sent
    """
    try:
        EmailStr.validate(invitation.recipient_mail)
    except EmailError:
        raise HTTPException(
            status_code=422,
            detail=INVALID_EMAIL_ADDRESS_ERROR_MESSAGE)

    if not send_email_invitation(
            sender_name=invitation.sender_name,
            recipient_name=invitation.recipient_name,
            recipient_mail=invitation.recipient_mail,
            background_tasks=background_task):
        raise HTTPException(status_code=422, detail="Couldn't send the email!")
    return RedirectResponse(invitation.send_to, status_code=303)
Ejemplo n.º 2
0
 def confirm_mail(cls, email: str) -> Union[ValueError, str]:
     """Validating email is valid mail address."""
     try:
         EmailStr.validate(email)
         return email
     except EmailError:
         raise ValueError("address is not valid")
Ejemplo n.º 3
0
def verify_email_pattern(email: str) -> bool:
    """
    This function checks the correctness
    of the entered email address
    :param email: str, the entered email address
    :return: bool,
    True if the entered email address is correct,
    False if the entered email address is incorrect.
    """
    try:
        EmailStr.validate(email)
        return True
    except EmailError:
        return False
Ejemplo n.º 4
0
def insert_default_user(database_connection):
    db = database_connection
    created_user = create_user(
        db,
        UserSchema(email=EmailStr("*****@*****.**"), username="******", password="******"),
    )
    yield created_user
Ejemplo n.º 5
0
async def send_mail(email: EmailStr):

    template = """
        <html>
        <body>
          
        <p>Hi !!!
        <br>Thanks for using fastapi mail, keep using it..!!!</p>
  
        </body>
        </html>
        """

    message = MessageSchema(
        subject="Fastapi-Mail module",
        # List of recipients, as many as you can pass
        recipients=email.dict().get("email"),
        body=template,
        subtype="html"
    )

    fm = FastMail(conf)
    await fm.send_message(message)
    print(message)

    return JSONResponse(status_code=200, content={"message": "email has been sent"})
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
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"
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
def _create_subscription(email: str = Form(...)):
    try:
        EmailStr.validate(email)
    except (EmailError, EmailSyntaxError):
        return Response(content="Invalid email address", status_code=400)

    try:
        subscriptions.insert({
            "created_at": str(datetime.datetime.now()),
        }, email)
    except Exception:
        return Response(
            content="You are already subscribed to our mailing list",
            status_code=304)
    return Response(
        content="Thanks for subscribing to the TroepTroep event mailing list",
        status_code=200)
Ejemplo n.º 10
0
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")
Ejemplo n.º 11
0
 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
Ejemplo n.º 12
0
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'
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
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'
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
async def register(
    request: Request,
    email: EmailStr = Form(...),
    password: SecretStr = Form(...),
    password_confirm: SecretStr = Form(...),
):
    successful = False
    reason = None

    # check if the two passwords are the same
    if password == password_confirm:
        # check if the user already exists in the database
        if (
            await User.query.where(User.user_email == email.lower()).gino.first()
            is not None
        ):
            # if so set the corresponding reason
            reason = "Already registered."
        else:
            # if the user is not already in the database, insert their
            await User.create(
                user_uuid=uuid.uuid4(),
                user_email=email.lower(),
                user_password_hash=ph.hash(password.get_secret_value()),
            )
            # set successful to True after the insert was successful
            successful = True
    else:
        # The passwords are not the same. Set the corresponding reason.
        reason = "Passwords not equal."

    # render the response template. See the template file to know what is displayed when
    return main.templates.TemplateResponse(
        "register_response.html",
        {
            "request": request,
            "reason": reason,
            "successful": successful,
            "email": email.lower(),
        },
    )
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
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")
Ejemplo n.º 19
0
class UserSchema(BaseModel):
    # _id: ObjectId
    name: str = Field(...)
    email: str = EmailStr(...)
    password: str = Field(...)

    class Config:
        schema_extra = {
            "example ": {
                "name": "タロー",
                "email": "*****@*****.**",
                "password": "******"
            }
        }
Ejemplo n.º 20
0
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)
Ejemplo n.º 21
0
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)
Ejemplo n.º 22
0
async def login(
    request: Request, email: EmailStr = Form(...), password: SecretStr = Form(...)
):
    successful = False
    reason = None
    token = None

    # search for a user model in the database. If there's no, return None
    if (
        user := await User.query.where(User.user_email == email.lower()).gino.first()
    ) is not None:

        # verify the password hash from the database against the password in the request
        try:
            if ph.verify(user.user_password_hash, password.get_secret_value()):
                # set to True since the password is correct
                successful = True

                # check if the password needs a rehash (e.g. because stronger hashing
                # options are used)
                # This is only possible on login because the client sends the password.
                if ph.check_needs_rehash(user.user_password_hash):
                    # update the new password hash in the database
                    await user.update(
                        user_password_hash=ph.hash(password.get_secret_value())
                    )

                # create a session token. Sessions are only validated by their signature
                token = jwt.encode(
                    {
                        "sub": str(user.user_uuid),
                        "exp": datetime.utcnow() + timedelta(weeks=1),
                    },
                    key=config.SESSION_SECRET.get_secret_value(),
                    algorithm="HS256",
                )
        except VerifyMismatchError:
            # the password hashes don't match -> wrong password
            successful = False
            reason = "Wrong password."
Ejemplo n.º 23
0
    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()
Ejemplo n.º 24
0
class InputSchema(BaseModel):
    email = EmailStr()
Ejemplo n.º 25
0
 def validate_email(self, email: str):
     """ Validate email address """
     if EmailStr.validate(email):
         return True
Ejemplo n.º 26
0
def test_email_str():
    class Model(BaseModel):
        v: EmailStr

    assert Model(v=EmailStr('*****@*****.**')).v == '*****@*****.**'
    assert Model(v='*****@*****.**').v == '*****@*****.**'
Ejemplo n.º 27
0
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"]),
)
Ejemplo n.º 28
0
    async def on_post(self,
                      base_url: Union[str, URL],
                      session: models.Session,
                      username: str,
                      email: str,
                      password: str,
                      confirm_password: str = None,
                      **kwargs) -> Union[HTMLResponse, RedirectResponse]:
        """ Handle POST requests """

        base_url = str(base_url)
        email = EmailStr.validate(email)

        def _register() -> Union[HTMLResponse, RedirectResponse]:

            try:
                self.validate_password(password)
            except ValueError as ex:
                content = self.render_form(error=str(ex), **kwargs)
                return HTMLResponse(status_code=400, content=content)

            if confirm_password is not None:
                # The only way for confirm_password to be None is if a
                # standard form doesn't include it, otherwise the value is ""
                if password != confirm_password:
                    content = self.render_form(
                        error="The specified passwords do not match.",
                        **kwargs)
                    return HTMLResponse(status_code=400, content=content)

            user = self.user_cls.get_by_email(session, email)
            if user:
                if user.username != username:
                    logger.info("Email '%s' already exists.", email)
                    # Is this an information leak?
                    content = self.render_form(
                        error="That email address already exists.", **kwargs)
                    return HTMLResponse(status_code=409, content=content)
                if user.confirmed:
                    logger.info("User '%s' already confirmed.", username)
                else:
                    # Unconfirmed, re-registration - update password
                    user.password = password
            else:
                user = self.user_cls(
                    username=username,
                    password=password,
                    email=email,
                )
                session.add(user)

            if not self.email_confirmation_required:
                user.confirmed_at = tz.utcnow()

            try:
                session.commit()
            except sqlalchemy.exc.IntegrityError:
                content = self.render_form(
                    error="That username already exists.", **kwargs)
                return HTMLResponse(status_code=409, content=content)

            if not self.email_confirmation_required:
                return RedirectResponse(url=self.location, status_code=303)

            self.send_email_confirmation(base_url,
                                         email,
                                         username=username,
                                         **kwargs)

            content = self.render(self.sent_template,
                                  username=username,
                                  email=email,
                                  **kwargs)
            return HTMLResponse(status_code=200, content=content)

        return await run_in_threadpool(_register)
Ejemplo n.º 29
0
 def validate_email(cls, v: Any) -> Optional[EmailStr]:
     if not v:
         return None
     return EmailStr(v)
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)
    )