예제 #1
0
파일: user.py 프로젝트: Tech-Dex/clockpoint
async def update_current(
    user_update: UserUpdate = Body(..., embed=True),
    user_current: UserTokenWrapper = Depends(get_current_user),
    conn: AsyncIOMotorClient = Depends(get_database),
) -> UserResponse:
    user_update.username = (
        None if user_update.username == user_current.username else user_update.username
    )
    user_update.email = (
        None if user_update.email == user_current.email else user_update.email
    )
    await check_availability_username_and_email(
        conn, user_update.email, user_update.username
    )
    user_db: UserDB = await update_user(conn, user_current, user_update)
    return UserResponse(user=UserTokenWrapper(**user_db.dict()))
 def update_user(self, user_update: UserUpdateIn) -> User:
     user = auth.update_user(
         user_update.id,
         email=user_update.email,
         password=user_update.password,
         display_name=user_update.name
     )
     user_data = UserUpdate(**user_update.dict(exclude={'id'}))
     # update in db
     return self.user_dao.update(user.uid, user_data)
예제 #3
0
def update_user_me(
    *,
    password: str = Body(None),
    full_name: str = Body(None),
    email: EmailStr = Body(None),
    current_user: UserInDB = Depends(get_current_active_user),
):
    """
    Update own user.
    """
    user_in = UserUpdate(**current_user.dict())
    if password is not None:
        user_in.password = password
    if full_name is not None:
        user_in.full_name = full_name
    if email is not None:
        user_in.email = email
    bucket = get_default_bucket()
    user = crud.user.update(bucket, username=current_user.username, user_in=user_in)
    return user
예제 #4
0
def update_user_me(
    *,
    db: Session = Depends(get_db),
    password: str = Body(None),
    full_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 full_name is not None:
        user_in.full_name = full_name
    if email is not None:
        user_in.email = email
    user = crud.user.update(db, user=current_user, user_in=user_in)
    return user
예제 #5
0
async def update_user_me(
        *,
        password: str = Body(None),
        fullname: str = Body(None),
        email: EmailStr = Body(None),
        current_user: UserInDB = Depends(get_current_active_user),
        db: DBClient = client):
    """
    Update own user
    """
    # user_in = UserUpdate(**current_user.dict())
    user_in = UserUpdate(**current_user)
    if password is not None:
        user_in.password = password
    if fullname is not None:
        user_in.fullname = fullname
    if user_in.email is not None:
        user_in.email = email
    user = await crud.update(db, current_user["_id"], user_in)
    if user:
        return utils.create_aliased_response(UserResponse(response=user))
    return utils.create_404_response()
예제 #6
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.password = passwordhash
    db_session.add(user)
    db_session.commit()
    db_session.refresh(user)
    return user
예제 #7
0
파일: test_user.py 프로젝트: bashhack/tyyni
def test_update_user(create_user):
    original_user = create_user()
    original_email_for_user = original_user.email
    random_email = random_lower_string()
    user_in = UserUpdate(email=random_email)
    user = crud.user.update_user(db_session,
                                 user_to_update=original_user,
                                 user_in=user_in)
    assert original_email_for_user != random_email
    assert user == original_user
    assert user.email == random_email

    assert original_user.email == random_email
예제 #8
0
    def update(self, obj: T, updated: UserUpdate) -> T:
        """Updates an existing User object.

        Parameters
        ----------
        obj : User
            The existing user to update.
        updated : UserUpdate
            The updated user data to use.

        Returns
        -------
        User
            The updated user object.

        """
        if updated.person:
            updated.person = self._uow.person.get_create_or_update(
                obj.person, updated.person)
        if updated.password:
            obj.hashed_password = get_password_hash(updated.password)
            updated.password = None
        return super().update(obj, updated)
def update_in_db(bucket: Bucket,
                 *,
                 username: str,
                 user_in: UserUpdate,
                 persist_to=0):
    user_doc_id = get_doc_id(username)
    stored_user = get(bucket, username=username)
    stored_user = stored_user.copy(update=user_in.dict(skip_defaults=True))
    if user_in.password:
        passwordhash = get_password_hash(user_in.password)
        stored_user.hashed_password = passwordhash
    data = jsonable_encoder(stored_user)
    with bucket.durability(persist_to=persist_to,
                           timeout=config.COUCHBASE_DURABILITY_TIMEOUT_SECS):
        bucket.upsert(user_doc_id, data)
    return stored_user
예제 #10
0
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()
    bucket = get_default_bucket()

    user = crud.user.get_by_email(bucket, email=email)
    if not user:
        user_in = UserCreate(username=email, email=email, password=password)
        user = crud.user.upsert(bucket, user_in=user_in, persist_to=1)
    else:
        user_in = UserUpdate(password=password)
        user = crud.user.update(bucket, user=user, user_in=user_in)

    return user_authentication_headers(get_server_api(), email, password)
def reset_password(token: str = Body(...), new_password: str = Body(...)):
    """
    Reset password.
    """
    username = verify_password_reset_token(token)
    if not username:
        raise HTTPException(status_code=400, detail="Invalid token")
    bucket = get_default_bucket()
    user = crud.user.get(bucket, username=username)
    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):
        raise HTTPException(status_code=400, detail="Inactive user")
    user_in = UserUpdate(name=username, password=new_password)
    user = crud.user.update(bucket, username=username, user_in=user_in)
    return {"msg": "Password updated successfully"}
예제 #12
0
async def reset_password(
    *,
    token: str = Body(...),
    new_password: str = Body(...),
    uow: UnitOfWork = Depends(get_uow)
) -> tp.Mapping[str, str]:
    """Resets a user's password from the given reset token.

    Parameters
    ----------
    token : str
        The password reset token to use.
    new_password : str
        The new, plaintext password to set.
    uow : UnitOfWork
        The unit of work object to use.

    Returns
    -------
    Mapping[str, str]
        The message from the password reset result.

    Raises
    ------
    APIException
        If the token isn't valid, or the user associated is not an
        active user.
    ObjectNotFoundException
        If the user specified by the decoded token does not exist.

    """
    email = verify_password_reset_token(token)
    if not email:
        raise APIError("Invalid token.")

    user = uow.user.get_by_email(email, raise_ex=True)
    if not uow.user.is_active(user):
        raise APIError("Inactive user.")

    updated_user = UserUpdate(password=new_password)
    with uow:
        uow.user.update(user, updated_user)
    return {"value": "Password updated successfully"}
예제 #13
0
파일: user.py 프로젝트: Tech-Dex/clockpoint
async def activate(
    user_current: UserTokenWrapper = Depends(get_current_user),
    conn: AsyncIOMotorClient = Depends(get_database),
) -> UserResponse:
    token_db: TokenDB = await get_token(conn, user_current.token)
    if token_db.subject == TokenSubject.ACTIVATE:
        if not token_db.used_at:
            user_db: UserDB = await update_user(
                conn, user_current, UserUpdate(is_active=True)
            )
            await update_token(
                conn, TokenUpdate(token=token_db.token, used_at=datetime.utcnow())
            )
            return UserResponse(user=UserTokenWrapper(**user_db.dict()))
        raise StarletteHTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Token has expired"
        )
    raise StarletteHTTPException(
        status_code=HTTP_403_FORBIDDEN, detail="Invalid activation"
    )
예제 #14
0
def test_update_user_returns_404_if_user_not_found(client, superuser_token_headers):
    server_api = get_server_api()
    user_id = 0

    random_email = random_lower_string()

    user_in = UserUpdate(email=random_email)

    request = {"email": user_in.email, "password": "******"}

    response = client.put(
        f"{server_api}{API_V1_STR}/users/{user_id}",
        json=request,
        headers=superuser_token_headers,
    )

    response_content = response.json()

    assert response.status_code == HTTP_404_NOT_FOUND
    assert response_content.get("message") == f"No user found with user_id: {user_id}"
예제 #15
0
파일: user.py 프로젝트: Tech-Dex/clockpoint
async def change_password(
    user_current: UserTokenWrapper = Depends(get_current_user),
    password: AnyStr = Body(..., embed=True),
    conn: AsyncIOMotorClient = Depends(get_database),
) -> UserResponse:
    token_db: TokenDB = await get_token(conn, user_current.token)
    if token_db.subject == TokenSubject.RECOVER:
        if not token_db.used_at:
            user_db: UserDB = await update_user(
                conn, user_current, UserUpdate(password=password)
            )
            await update_token(
                conn, TokenUpdate(token=token_db.token, used_at=datetime.utcnow())
            )
            return UserResponse(user=UserTokenWrapper(**user_db.dict()))
        raise StarletteHTTPException(
            status_code=HTTP_403_FORBIDDEN, detail="Token has expired"
        )
    raise StarletteHTTPException(
        status_code=HTTP_403_FORBIDDEN, detail="Invalid recovery"
    )
예제 #16
0
def test_update_user(client, create_user, superuser_token_headers):
    server_api = get_server_api()
    user = create_user()
    original_user_email = user.email

    random_email = random_lower_string()
    user_in = UserUpdate(email=random_email)

    request = {"email": user_in.email, "password": "******"}

    response = client.put(
        f"{server_api}{API_V1_STR}/users/{user.id}",
        json=request,
        headers=superuser_token_headers,
    )

    response_content = response.json()

    assert response.status_code == HTTP_200_OK
    assert response_content.get("id") == user.id
    assert original_user_email != random_email
    assert response_content.get("email") == random_email
예제 #17
0
 def update(self, id: str, user_update: UserUpdate) -> User:
     data = user_update.dict(exclude_none=True)
     doc_ref = self.collection_ref.document(id)
     doc_ref.update(data)
     return self.get(id)