Example #1
0
def update_user(
    data: UserUpdate,
    user: UserModel = Depends(deps.get_user),
    db: Session = Depends(deps.get_db),
    rdc: RedisCache = Depends(deps.get_redis)
) -> Any:
    """
    Endpoint for update current user
    """
    db_user = crud_user.get_user_by_email(db, data.email)
    if db_user and db_user.id != user.id:
        raise HTTPException(status_code=400,
                            detail='Endereço de email já registrador!')

    data.avatar = user.avatar
    data.is_active = user.is_active
    if not data.address and user.address:
        data.address = user.address

    user = crud_user.update(db, user, data)
    rdc.invalidate_cache_provider(user)
    if user.address:  #<-- if have an address, is a provider
        rdc.invalidate_cache_user(user)
        rdc.invalidate_cache_prefix("providers-list")

    return user
Example #2
0
def activate_random_user(db: Session, user: User) -> User:
    user_in = UserUpdate(
        name=user.name,
        surname=user.surname,
        email=user.email,
        is_active=True,
    )
    if user.address:
        user_in.address = user.address
    return crud_user.update(db, user, user_in)
def test_update_user(db: Session) -> None:
    email = random_email()
    password = random_lower_string()
    user_in = UserCreate(email=email, password=password)
    user = services.user.create_user(user_in.to_dto())
    new_password = random_lower_string()
    user_in_update = UserUpdate(password=new_password)
    services.user.update_user(user.provider_uuid, user.uuid,
                              user_in_update.to_dto())
    user_2 = services.user.get_user(user.uuid)
    assert user_2
    assert user.email == user_2.email
    assert verify_password(new_password, user_2.password)
Example #4
0
 def update(self, db: Session, *, db_obj: User, obj_in: UserUpdate) -> User:
     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
     return super().update(db, db_obj=db_obj, obj_in=update_data)
def update_user_me(
        *,
        password: str = Body(None),
        email: EmailStr = Body(None),
        current_user: DBUser = Depends(get_current_active_user),
):
    """
    Update own user.
    """
    current_user_data = current_user.to_mongo()
    user_in = UserUpdate(**current_user_data)
    if password is not None:
        user_in.password = password
    if email is not None:
        user_in.email = email
    user = crud.user.update(db_obj=current_user, obj_in=user_in)
    return user
Example #6
0
 def update(self, db_session: Session, *, db_obj: User, obj_in: UserUpdate) -> User:
     if obj_in.password:
         update_data = obj_in.dict(exclude_unset=True)
         hashed_password = get_password_hash(obj_in.password)
         del update_data["password"]
         update_data["hashed_password"] = hashed_password
         use_obj_in = UserInDB.parse_obj(update_data)
     return super().update(db_session, db_obj=db_obj, obj_in=use_obj_in)
def test_update_user(db: Session, new_user: User) -> None:
    new_password = random_lower_string()
    user_in_update = UserUpdate(password=new_password, is_superuser=True)
    crud.user.update(db, db_obj=new_user, obj_in=user_in_update)
    user = crud.user.get(db, id=new_user.id)
    assert user
    assert user.username == new_user.username
    assert user.email == new_user.email
    assert verify_password(new_password, user.hashed_password)
Example #8
0
def request_user_activate(
    data: UserActive, db: Session = Depends(deps.get_db)) -> Any:
    """
    Endpoint for user activate
    """
    user_id = security.verify_token(data.token, 'activate')
    user = crud_user.get_user_by_id(db, user_id)
    if not user:
        raise HTTPException(status_code=404, detail="Usuário não encontrado!")

    if user.is_active:
        raise HTTPException(status_code=400, detail="Conta já verificada")

    user_in = UserUpdate(**jsonable_encoder(user))
    user_in.is_active = True
    crud_user.update(db, user, user_in)
    if user.address:
        return {"type": "provider"}

    return {"type": "user"}
Example #9
0
def authentication_token_from_email(
    *, client: TestClient, email: str, db: Session
) -> Dict[str, str]:
    """
    Return a valid token for the user with given email.

    If the user doesn't exist it is created first.
    """
    password = random_lower_string()
    user = services.user.get_user_by_email(email)
    if not user:
        user_in_create = UserCreate(email=email, password=password)
        user = services.user.create_user(user_in_create.to_dto())
    else:
        user_in_update = UserUpdate(password=password)
        user = services.user.update_user(
            user.provider_uuid, user.uuid, user_in_update.to_dto()
        )

    return user_authentication_headers(client=client, email=email, password=password)
def test_update_user():
    password = random_lower_string()
    username = random_lower_string()
    user_in = UserCreate(email=username, password=password, is_superuser=True)
    user = crud.user.create(db_session, obj_in=user_in)
    new_password = random_lower_string()
    user_in = UserUpdate(password=new_password, is_superuser=True)
    crud.user.update(db_session, db_obj=user, obj_in=user_in)
    user_2 = crud.user.get(db_session, id=user.id)
    assert user.email == user_2.email
    assert verify_password(new_password, user_2.hashed_password)
Example #11
0
def test_update_user(db: Session) -> None:
    password = random_lower_string()
    email = random_email()
    user_in = UserCreate(email=email, password=password)
    user = crud.user.create(db, obj_in=user_in)
    new_username = random_lower_string()
    user_in_update = UserUpdate(full_name=new_username)
    crud.user.update(db, db_obj=user, obj_in=user_in_update)
    user_2 = crud.user.get(db, id=user.id)
    assert user_2
    assert user.email == user_2.email
    assert new_username == user_2.full_name
Example #12
0
def update_user_me(
        *,
        db: Session = Depends(get_db),
        user_in: OpenUserUpdate,
        current_user: DBUser = Depends(get_current_active_user),
):
    """
    Update own user.
    """

    current_user_data = jsonable_encoder(current_user)
    update_user_in = UserUpdate(**current_user_data)
    if user_in.password is not None:
        update_user_in.password = user_in.password
    if user_in.email is not None:
        update_user_in.email = user_in.email
    if user_in.full_name is not None:
        update_user_in.full_name = user_in.full_name

    user = crud.user.update(db, user=current_user, user_in=update_user_in)
    return user
Example #13
0
def update_user_me(
        *,
        db: Session = Depends(get_db),
        password: str = Body(None),
        name: str = Body(None),
        email: EmailStr = Body(None),
        current_user: DBUser = Depends(get_current_active_user),
):
    """
    Update own user.
    """
    current_user_data = jsonable_encoder(current_user)
    user_in = UserUpdate(**current_user_data)
    if password is not None:
        user_in.password = password
    if name is not None:
        user_in.full_name = name
    if email is not None:
        user_in.email = email
    user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
    return user
def test_update_user_not_password(db: Session) -> None:
    password = random_lower_string()
    email = random_email()
    user_in = UserCreate(email=email, password=password, is_superuser=True)
    user = crud.user.create(db, obj_in=user_in)
    full_name = random_lower_string()
    user_in_update = UserUpdate(full_name=full_name, is_superuser=True)
    crud.user.update(db, db_obj=user, obj_in=user_in_update)
    user_2 = crud.user.get(db, id=user.id)
    assert user_2
    assert user.email == user_2.email
    assert user.full_name == user_2.full_name
Example #15
0
def test_update_user(db: Session) -> None:
    password = random_lower_string()
    email = random_email()
    user_in = UserCreate(email=email, password=password, is_superuser=True)
    user = crud.user.create(db, obj_in=user_in)
    new_password = random_lower_string()
    user_in_update = UserUpdate(password=new_password, is_superuser=True)
    crud.user.update(db, db_obj=user, obj_in=user_in_update)
    user_2 = crud.user.get(db, id=user.id)
    assert user_2
    assert user.email == user_2.email
    assert verify_password(new_password, user_2.hashed_password)
Example #16
0
def update(db_session: Session, *, user: User, user_in: UserUpdate) -> User:
    user_data = jsonable_encoder(user)
    update_data = user_in.dict(skip_defaults=True)
    for field in user_data:
        if field in update_data:
            setattr(user, field, update_data[field])
    if user_in.password:
        passwordhash = get_password_hash(user_in.password)
        user.hashed_password = passwordhash
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)
    return user
Example #17
0
async def upload_avatar(user: UserModel = Depends(deps.get_user),
                        file: UploadFile = File(...),
                        db: Session = Depends(deps.get_db),
                        rdc: RedisCache = Depends(deps.get_redis)) -> Any:
    """
    Endpoint for upload user avatar
    """
    fileRead = await file.read()
    if user.avatar:
        avatar = media.update(fileRead, user.avatar)

    else:
        avatar = media.save(fileRead)

    user_in = UserUpdate(**jsonable_encoder(user))
    user_in.avatar = avatar
    user = crud_user.update(db, user, user_in)
    rdc.invalidate_cache_provider(user)
    if user.address:  #<-- if have an address, is a provider
        rdc.invalidate_cache_prefix("providers-list")
        rdc.invalidate_cache_user(user)

    return user
def authentication_token_from_email(email):
    """
    Return a valid token for the user with given email.

    If the user doesn't exist it is created first.
    """
    password = random_lower_string()
    user = crud.user.get_by_email(db_session, email=email)
    if not user:
        user_in = UserCreate(username=email, email=email, password=password)
        user = crud.user.create(db_session=db_session, obj_in=user_in)
    else:
        user_in = UserUpdate(password=password)
        user = crud.user.update(db_session, obj_in=user, db_obj=user_in)

    return user_authentication_headers(get_server_api(), email, password)
async def test_cachedb_update_user(db: Session, redis: aioredis.Redis,
                                   new_user: User):
    user = await crud.user_cachedb.get(db, redis, id=new_user.id)
    new_password = random_lower_string()
    user_in_update = UserUpdate(password=new_password)
    await crud.user_cachedb.update(db,
                                   redis,
                                   cache_obj=user,
                                   obj_in=user_in_update)
    user = await crud.user_cachedb.get(db, redis, id=new_user.id)
    db_user = crud.user.get(db, id=new_user.id)
    assert user
    assert user.username == new_user.username
    assert user.email == new_user.email
    assert verify_password(new_password, user.hashed_password)
    assert verify_password(new_password, db_user.hashed_password)
Example #20
0
def authentication_token_from_email(
    *, client: TestClient, email: str, db: Session
) -> Dict[str, str]:
    """
    Return a valid token for the user with given email.

    If the user doesn't exist it is created first.
    """
    password = random_lower_string()
    user = crud.user.get_by_username(db, email=email)
    if not user:
        user_in_create = UserCreate(username=email, email=email, password=password)
        user = crud.user.create(db, obj_in=user_in_create)
    else:
        user_in_update = UserUpdate(password=password)
        user = crud.user.update(db, db_obj=user, obj_in=user_in_update)

    return user_authentication_headers(client=client, email=email, password=password)
Example #21
0
def update(
      user_to_update: schemas.UserUpdate,
      db_session: Session = Depends(get_db),
      current_user: models.User = Depends(get_current_user)
):
    db_user = crud.get_by_email(db_session, user_to_update.email)

    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f'User with email "{user_to_update.email}" not found.'
        )

    return crud.update(
        db_session,
        db_user=db_user,
        user_to_update=user_to_update.dict(exclude={'email'}),
        updated_by_admin=current_user.is_admin
    )
 def reassign_schedulers(self, db: Session):
     all_users = db.query(self.model).all()
     for found_user in all_users:
         old_repetition = found_user.repetition_model
         new_repetition = Repetition.select_model()
         found_user = crud.user.update(
             db,
             db_obj=found_user,
             obj_in=UserUpdate(repetition_model=new_repetition))
         change_assignment(user=found_user, repetition_model=new_repetition)
         history_in = HistoryCreate(time=datetime.now(timezone('UTC')),
                                    user_id=found_user.id,
                                    log_type=Log.reassign_model,
                                    details={
                                        "old_repetition_model":
                                        old_repetition,
                                        "new_repetition_model":
                                        found_user.repetition_model
                                    })
         crud.history.create(db=db, obj_in=history_in)
    def reassign_scheduler(
        self,
        db: Session,
        user: User,
        *,
        repetition_model: Repetition = None
    ) -> Union[User, requests.exceptions.RequestException,
               json.decoder.JSONDecodeError]:
        try:
            old_repetition = user.repetition_model
            new_repetition = repetition_model if repetition_model else Repetition.select_model(
            )
            found_user = crud.user.update(
                db,
                db_obj=user,
                obj_in=UserUpdate(repetition_model=new_repetition))
            response = change_assignment(user=found_user,
                                         repetition_model=new_repetition)

            history_in = HistoryCreate(time=datetime.now(timezone('UTC')),
                                       user_id=found_user.id,
                                       log_type=Log.reassign_model,
                                       details={
                                           "old_repetition_model":
                                           old_repetition,
                                           "new_repetition_model":
                                           found_user.repetition_model
                                       })
            crud.history.create(db=db, obj_in=history_in)
            return found_user
        except requests.exceptions.RequestException as e:
            capture_exception(e)
            return e
        except json.decoder.JSONDecodeError as e:
            capture_exception(e)
            return e
def test_update_user_password_to_empty_is_not_allowed():
    with pytest.raises(ValidationError):
        UserUpdate(password=None)
    with pytest.raises(ValidationError):
        UnprivilegedUserUpdate(password=None)
Example #25
0
 def register_bolo(self, db: Session, *, id: int):
     usr = self.get_or_404(db, id=id)
     update_user = UserUpdate(bolos=usr.bolos + 1, latest_bolo=datetime.now())
     return self.update(db, db_obj=usr, obj_in=update_user)
 def update(
     self, db_session: Session, *, db_obj: User, obj_in: UserUpdate
 ) -> User:
     if obj_in.password:
         obj_in.hashed_password = get_password_hash(obj_in.password)
     return super().update(db_session, db_obj=db_obj, obj_in=obj_in)