Exemple #1
0
    async def update(self, db: AsyncSession, *, db_obj: models.User,
                     obj_in: Union[UserUpdate, Dict[str, Any]]) -> models.User:

        if isinstance(obj_in, dict):
            update_data = obj_in
        else:
            update_data = obj_in.dict(exclude_unset=True)
        if update_data.get("password"):
            hashed_password = get_password_hash(update_data["password"])
            del update_data["password"]
            update_data["hashed_password"] = hashed_password
        if update_data.get("roles") or len(update_data["roles"]) == 0:
            roles = await db.execute(
                select(models.Role).filter(models.Role.name.in_(obj_in.roles)))
            db_obj.roles = roles.scalars().all()
            del update_data["roles"]
        if update_data.get("study_areas") or len(
                update_data["study_areas"]) == 0:
            study_areas = await db.execute(
                select(models.StudyArea).filter(
                    models.StudyArea.id.in_(obj_in.study_areas)))
            db_obj.study_areas = study_areas.scalars().all()
            del update_data["study_areas"]

        return await super().update(db, db_obj=db_obj, obj_in=update_data)
Exemple #2
0
async def reset_password(
        token: str = Body(...),
        new_password: str = Body(...),
        db: AsyncSession = Depends(deps.get_db),
) -> Any:
    """
    Reset password
    """
    email = verify_token(token)
    if not email:
        raise HTTPException(status_code=400, detail="Invalid token")
    user = await crud.user.get_by_key(db, key="email", value=email)
    if not user:
        raise HTTPException(
            status_code=404,
            detail="The user with this username does not exist in the system.",
        )
    elif not crud.user.is_active(user[0]):
        raise HTTPException(status_code=400, detail="Inactive user")
    else:
        user = user[0]

    hashed_password = get_password_hash(new_password)
    user.hashed_password = hashed_password
    db.add(user)
    await db.commit()
    return {"msg": "Password updated successfully"}
Exemple #3
0
 def create(self, *, obj_in: UserCreate) -> User:
     db_obj = UserDbModel(
         username=obj_in.username,
         is_superuser=obj_in.is_superuser,
         password_hash=get_password_hash(obj_in.password),
     )
     self.db.add(db_obj)
     self.db.commit()
     self.db.refresh(db_obj)
     return self.schema.from_orm(db_obj)
Exemple #4
0
 async def create(self, db: AsyncSession, *, obj_in: UserCreate) -> User:
     db_obj = User(
         email=obj_in.email,
         hashed_password=get_password_hash(obj_in.password),
         full_name=obj_in.full_name,
     )
     db.add(db_obj)
     await db.commit()
     await db.refresh(db_obj)
     return db_obj
Exemple #5
0
async def test_user_creation(db_session):
    user = User(
        name="Marcelo Lino",
        email="*****@*****.**",
        password=get_password_hash("my_password"),
        cpf="29931096004",
    )
    db_session.add(user)
    assert user.id is None
    await db_session.commit()
    assert isinstance(user.id, int)
Exemple #6
0
 async def update(self, db: AsyncSession, *, db_obj: User,
                  obj_in: Union[UserUpdate, Dict[str, Any]]) -> User:
     if isinstance(obj_in, dict):
         update_data = obj_in
     else:
         update_data = obj_in.dict(exclude_unset=True)
     if update_data["password"]:
         hashed_password = get_password_hash(update_data["password"])
         del update_data["password"]
         update_data["hashed_password"] = hashed_password
     return await super().update(db, db_obj=db_obj, obj_in=update_data)
Exemple #7
0
 def update(
     self, *, db_obj: UserDbModel, obj_in: Union[UserUpdate, Dict[str, Any]]
 ) -> User:
     if isinstance(obj_in, dict):
         update_data = obj_in
     else:
         update_data = obj_in.dict(exclude_unset=True)
     if update_data["password"]:
         hashed_password = get_password_hash(update_data["password"])
         update_data.pop("password")
         update_data["password_hash"] = hashed_password
     return super().update(db_obj=db_obj, obj_in=update_data)
Exemple #8
0
    def test_login_ok(self, authentication_service):
        # Load IO

        # Mock internal service
        test_user = deepcopy(mock_io_data.user1)
        test_user.password_hash = get_password_hash("1234")
        crud_user = authentication_service.get_crud_user_mock()
        crud_user.get_by_username.return_value = test_user

        # Method under test
        response = authentication_service.login("franco", "1234")

        # Assertions
        assert response == test_user
Exemple #9
0
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    user_table = op.create_table(
        "user",
        sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("name", sa.String(), nullable=False),
        sa.Column("cpf", sa.String(length=11), nullable=False),
        sa.Column(
            "email",
            sqlalchemy_utils.types.email.EmailType(length=255),
            nullable=False,
        ),
        sa.Column("password", sa.String(), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("cpf"),
        sa.UniqueConstraint("email"),
    )
    op.create_index(op.f("ix_user_id"), "user", ["id"], unique=True)
    op.create_table(
        "purchase",
        sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
        sa.Column("created_at", sa.DateTime(), nullable=False),
        sa.Column("updated_at", sa.DateTime(), nullable=True),
        sa.Column("code", sa.String(), nullable=False),
        sa.Column("purchase_date", sa.Date(), nullable=False),
        sa.Column("reseller_cpf", sa.String(length=11), nullable=False),
        sa.Column("status", sa.String(), nullable=False),
        sa.Column("value", sa.DECIMAL(scale=2), nullable=True),
        sa.Column("user_id", sa.BigInteger(), nullable=False),
        sa.ForeignKeyConstraint(("user_id",), ["user.id"], ondelete="CASCADE"),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index(op.f("ix_purchase_id"), "purchase", ["id"], unique=True)

    op.bulk_insert(
        user_table,
        [
            {
                "id": 1,
                "name": "Administrador",
                "password": get_password_hash("admin"),
                "email": "*****@*****.**",
                "cpf": "76028950025",
                "created_at": datetime.datetime.now(),
            }
        ],
    )
Exemple #10
0
 async def create(self, db: AsyncSession, *,
                  obj_in: UserCreate) -> models.User:
     db_obj = models.User.from_orm(obj_in)
     db_obj.hashed_password = get_password_hash(obj_in.password)
     roles = await db.execute(
         select(models.Role).filter(models.Role.name.in_(obj_in.roles)))
     db_obj.roles = roles.scalars().all()
     study_areas = await db.execute(
         select(models.StudyArea).filter(
             models.StudyArea.id.in_(obj_in.study_areas)))
     db_obj.study_areas = study_areas.scalars().all()
     db.add(db_obj)
     await db.commit()
     await db.refresh(db_obj)
     return db_obj
def registration(
        item_in: schemas.UserCreate,
        db: Session = Depends(deps.get_db),
):
    user = models.User(
        email=item_in.email.lower(
        ),  # TODO: Create a functional index to force uniqueness on  the DB side
        username=item_in.username,
        salt="",
        password=get_password_hash(item_in.password),
        active=False,
        verification_code=randrange(100000, 999999),
    )

    db.add(user)
    try:
        db.commit()
    except IntegrityError:
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="The user with this email already exists in the system.",
        )
    db.refresh(user)

    verification_link = f"{settings.PUBLIC_URL}/auth/confirm-code-verification/{user.id}/{user.verification_code}"
    EmailCoreService().add_message_to_queue(
        user.email,
        "account_verification_code_subject.html",
        "account_verification_code.html",
        {
            "username": user.username,
            "verification_link": verification_link
        },
    )

    return user
Exemple #12
0
def user_model(user_data) -> User:
    data = deepcopy(user_data)
    data["password"] = get_password_hash(user_data["password"])
    return User(**data)
Exemple #13
0
def test_get_password_hash(password_hash):
    password = "******"
    assert get_password_hash(password) != password