Exemplo n.º 1
0
async def change_password(
    request: Request,
    user_uuid: uuid.UUID = Depends(get_current_user),
    password: SecretStr = Form(...),
    new_password: SecretStr = Form(...),
    new_password_confirm: SecretStr = Form(...),
):
    # check if the two new password fields are equal
    if new_password == new_password_confirm:
        try:
            # get the current (old) user from the database
            if user := await User.get(user_uuid):
                # verify the the provided password`s hash matches the old in the
                # database or else raise an error
                ph.verify(user.user_password_hash, password.get_secret_value())

                # update the password hash to the new password in the database
                await user.update(
                    user_password_hash=ph.hash(new_password.get_secret_value())
                ).apply()

                # render the response page
                return main.templates.TemplateResponse(
                    "settings_updated.html", {"request": request, "setting": "password"}
                )
            else:
                # Since ``get_current_user`` only checks if session keys signature is
                # correct, it is possible that a user does not exist in the database.
                # Usually this shouldn't be the case. It can happen if you sign keys
                # outside of the application or a user is deleted but the session keys
                # are still valid.
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="User not found. That's strange and shouldn't be the case.",
                )
Exemplo n.º 2
0
class AzureMSSQLConnector(ToucanConnector):
    """
    Import data from Microsoft Azure SQL Server.
    """

    data_source_model: AzureMSSQLDataSource

    host: str = Field(
        ...,
        description='The domain name (preferred option as more dynamic) or '
        'the hardcoded IP address of your database server',
    )

    user: str = Field(..., description='Your login username')
    password: SecretStr = Field('', description='Your login password')
    connect_timeout: int = Field(
        None,
        title='Connection timeout',
        description=
        'You can set a connection timeout in seconds here, i.e. the maximum length of '
        'time you want to wait for the server to respond. None by default',
    )

    def get_connection_params(self, *, database=None):
        base_host = re.sub(f'.{CLOUD_HOST}$', '', self.host)
        user = f'{self.user}@{base_host}' if '@' not in self.user else self.user

        if not self.password:
            self.password = SecretStr('')

        con_params = {
            'driver': '{ODBC Driver 17 for SQL Server}',
            'server': f'{base_host}.{CLOUD_HOST}',
            'database': database,
            'user': user,
            'password': self.password.get_secret_value(),
            'timeout': self.connect_timeout,
        }
        # remove None values
        return {k: v for k, v in con_params.items() if v is not None}

    def _retrieve_data(self, datasource: AzureMSSQLDataSource) -> pd.DataFrame:
        connection = pyodbc.connect(**self.get_connection_params(
            database=datasource.database))

        query_params = datasource.parameters or {}
        df = pandas_read_sql(
            datasource.query,
            con=connection,
            params=query_params,
            convert_to_qmark=True,
            render_user=True,
        )

        connection.close()
        return df
Exemplo n.º 3
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."
Exemplo n.º 4
0
    def set_valid_password(cls: BaseModel, v: SecretStr) -> str:
        def valid_pass(password: str) -> bool:
            valid_length = len(password) >= PASS_MIN_LENGTH
            upper = any(c.isupper() for c in password)
            lower = any(c.islower() for c in password)
            special = not password.isalnum()
            return valid_length and upper and lower and special

        def hash_password(password: str) -> str:
            return pwd_context.hash(password)

        password = v.get_secret_value()
        if not v or not valid_pass(password):
            raise ValueError(INVALID_PASS_MSG)
        return hash_password(password)
async def autenticate_user(
    username: str = Form(...),
    password: SecretStr = Form(...)):

    password_ = password.get_secret_value()

    user = get_user(username, password_)

    if user is None:
        raise HTTPException(status_code=401, detail="User not found")

    user['token'] = 145

    user = {k.lower(): v for k, v in user.items()}

    return user
async def register_user(
    email: EmailStr = Form(...),
    username: str = Form(...),
    password: SecretStr = Form(...),
    photo: Optional[UploadFile] = Form(None)):

    user = {"email": email, "username": username}

    if check_email(email):
        raise HTTPException(status_code=409, detail="Email already registered")

    if check_username(username):
        raise HTTPException(status_code=409, detail="Username already taken")

    password_ = password.get_secret_value()

    if not create_user(email, username, password_):
        raise HTTPException(status_code=500, detail="Internal server error")

    return user
Exemplo n.º 7
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(),
        },
    )
Exemplo n.º 8
0
 def set_valid_password(cls: BaseModel, v: SecretStr) -> str:
     password = v.get_secret_value()
     if not v or not valid_pass(password):
         raise ValueError(INVALID_PASS_MSG)
     return hash_password(password)
Exemplo n.º 9
0
 def constrain_password(cls, value: SecretStr, values) -> SecretStr:
     v = value.get_secret_value()
     assert len(v) >= 5, 'password must be at least five characters long'
     assert v not in values[
         'server'], 'password cannot be part of server name'
     return value
class MicroStrategyConnector(ToucanConnector):
    """
    Import data from MicroStrategy using the [JSON Data API](http://bit.ly/2HCzf04) for cubes and
    reports.
    """

    data_source_model: MicroStrategyDataSource

    base_url: HttpUrl = Field(
        ...,
        title='API base URL',
        description='The URL of your MicroStrategy environment API. For '
        'example '
        '"https://demo.microstrategy.com/MicroStrategyLibrary2/api/"',
        examples=['https://demo.microstrategy.com/MicroStrategyLibrary2/api/'],
    )
    username: str = Field(..., description='Your login username')
    password: SecretStr = Field('', description='Your login password')
    project_id: str = Field(
        ...,
        title='projectID',
        description='The unique ID of your MicroStrategy project. '
        'In the form "B7CA92F04B9FAE8D941C3E9B7E0CD754"',
        examples=['https://demo.microstrategy.com/MicroStrategyLibrary2/api/'],
    )

    def _retrieve_metadata(self, data_source: MicroStrategyDataSource) -> pd.DataFrame:
        client = Client(
            self.base_url, self.project_id, self.username, self.password.get_secret_value()
        )

        results = client.list_objects(
            [st.value for st in Subtypes], data_source.id, data_source.offset, data_source.limit
        )
        df = json_normalize(results['result'])
        subtypes_mapping = {st.value: st.name for st in Subtypes}
        df['subtype'] = df['subtype'].replace(subtypes_mapping)
        return df

    def _retrieve_data(self, data_source: MicroStrategyDataSource) -> pd.DataFrame:
        """Retrieves cube or report data, flattens return dataframe"""
        if data_source.dataset == Dataset.search:
            return self._retrieve_metadata(data_source)
        if not self.password:
            self.password = SecretStr('')
        client = Client(
            self.base_url, self.project_id, self.username, self.password.get_secret_value()
        )

        query_func = getattr(client, data_source.dataset)
        if not data_source.viewfilter:
            results = query_func(
                id=data_source.id, offset=data_source.offset, limit=data_source.limit
            )
        else:
            results = query_func(id=data_source.id, limit=0)
            dfn = get_definition(results)
            data_source.viewfilter = nosql_apply_parameters_to_query(
                data_source.viewfilter, data_source.parameters
            )
            viewfilter = fill_viewfilter_with_ids(data_source.viewfilter, dfn)
            results = query_func(
                id=data_source.id,
                viewfilter=viewfilter,
                offset=data_source.offset,
                limit=data_source.limit,
            )

        # Get a list of attributes and metrics
        attributes = get_attr_names(results)
        metrics = get_metric_names(results)

        # get data based on attributes and metrics
        rows = flatten_json(results['result']['data']['root'], attributes, metrics)
        return json_normalize(rows)
Exemplo n.º 11
0
def get_password_hash(password: SecretStr) -> str:
    return pwd_context.hash(password.get_secret_value())
Exemplo n.º 12
0
def verify_password(plain_password: SecretStr, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password.get_secret_value(), hashed_password)
async def login_user(client: AsyncClient, email: EmailStr, password: SecretStr):
    path = "/auth/login"
    r = await client.post(
        path, json={"email": email, "password": password.get_secret_value()}
    )
    r.raise_for_status()
 def verify(self, *, hashed_password: str,
            plain_password: pydantic.SecretStr) -> bool:
     return self._context.verify(plain_password.get_secret_value(),
                                 hashed_password)
Exemplo n.º 15
0
 def is_valid_shared_key(self, shared_key: SecretStr) -> bool:
     return (
         shared_key.get_secret_value() == self.settings.shared_key.get_secret_value()
     )
Exemplo n.º 16
0
def dummy_hasher(plain_password: pydantic.SecretStr) -> str:
    return plain_password.get_secret_value() * 15