def route_users_put( *, username: str, user_in: UserInUpdate, current_user: UserInDB = Depends(get_current_user), ): """ Update a user """ if not check_if_user_is_active(current_user): raise HTTPException(status_code=400, detail="Inactive user") elif not check_if_user_is_superuser(current_user): raise HTTPException( status_code=400, detail="The user doesn't have enough privileges" ) bucket = get_default_bucket() user = get_user(bucket, username) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system", ) user = update_user(bucket, user_in) return user
def route_users_post( *, user_in: UserInCreate, current_user: UserInDB = Depends(get_current_user) ): """ Create new user """ if not check_if_user_is_active(current_user): raise HTTPException(status_code=400, detail="Inactive user") elif not check_if_user_is_superuser(current_user): raise HTTPException( status_code=400, detail="The user doesn't have enough privileges" ) bucket = get_default_bucket() user = get_user(bucket, user_in.username) if user: raise HTTPException( status_code=400, detail="The user with this username already exists in the system.", ) user = upsert_user(bucket, user_in, persist_to=1) if config.EMAILS_ENABLED and user_in.email: send_new_account_email( email_to=user_in.email, username=user_in.username, password=user_in.password ) return user
def route_users_post( *, username, password, admin_channels=[], admin_roles=[], disabled=False, email=None, full_name=None, ): current_user = get_current_user() if not current_user: abort(400, "Could not authenticate user with provided token") elif not check_if_user_is_active(current_user): abort(400, "Inactive user") elif not check_if_user_is_superuser(current_user): abort(400, "The user doesn't have enough privileges") bucket = get_default_bucket() user = get_user(bucket, username) if user: return abort(400, f"The user with this username already exists in the system.") user_in = UserInCreate( username=username, password=password, admin_channels=admin_channels, admin_roles=admin_roles, disabled=disabled, email=email, full_name=full_name, ) user = upsert_user(bucket, user_in) if config.EMAILS_ENABLED: send_new_account_email(email_to=email, username=username, password=password) return user
def route_users_post_open( *, username: str = Body(...), password: str = Body(...), email: EmailStr = Body(None), full_name: str = Body(None), ): """ Create new user without the need to be logged in """ if not config.USERS_OPEN_REGISTRATION: raise HTTPException( status_code=403, detail="Open user resgistration is forbidden on this server", ) bucket = get_default_bucket() user = get_user(bucket, username) if user: raise HTTPException( status_code=400, detail="The user with this username already exists in the system", ) user_in = UserInCreate( username=username, password=password, email=email, full_name=full_name ) user = upsert_user(bucket, user_in, persist_to=1) return user
def create_random_user(): email = random_lower_string() password = random_lower_string() user_in = UserCreate(username=email, email=email, password=password) bucket = get_default_bucket() user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) return user
def create_user_open( *, password: str = Body(...), email: EmailStr = Body(...), full_name: str = Body(None), ) -> Any: """ Create new user without the need to be logged in. """ if not settings.USERS_OPEN_REGISTRATION: raise HTTPException( status_code=403, detail="Open user registration is forbidden on this server", ) db = get_default_bucket() user = crud.user.get_by_email(email=email) if user: raise HTTPException( status_code=400, detail="The user with this username already exists in the system", ) user_in = schemas.UserCreate(password=password, email=email, full_name=full_name) user = crud.user.create(obj_in=user_in) return user
def test_retrieve_users(superuser_token_headers): server_api = get_server_api() username = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=username, email=username, password=password) bucket = get_default_bucket() user = upsert_user(bucket, user_in, persist_to=1) username2 = random_lower_string() password2 = random_lower_string() user_in2 = UserInCreate(username=username2, email=username2, password=password2) user2 = upsert_user(bucket, user_in, persist_to=1) r = requests.get(f"{server_api}{config.API_V1_STR}/users/", headers=superuser_token_headers) all_users = r.json() assert len(all_users) > 1 for user in all_users: assert "username" in user assert "admin_roles" in user
def create_user_open( *, username: str = Body(...), password: str = Body(...), email: EmailStr = Body(None), full_name: str = Body(None), ): """ Create new user without the need to be logged in. """ if not config.USERS_OPEN_REGISTRATION: raise HTTPException( status_code=403, detail="Open user resgistration is forbidden on this server", ) bucket = get_default_bucket() user = crud.user.get(bucket, username=username) if user: raise HTTPException( status_code=400, detail="The user with this username already exists in the system", ) user_in = UserCreate(username=username, password=password, email=email, full_name=full_name) user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) if config.EMAILS_ENABLED and user_in.email: send_new_account_email(email_to=user_in.email, username=user_in.username, password=user_in.password) return user
def update(*, 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 obj_data = jsonable_encoder(update_data) for field in obj_data: if field in update_data: setattr(db_obj, field, update_data[field]) query_str = {"email": f"{db_obj.email}"} newvalues = {"$set": obj_data} db = get_default_bucket() collection = db["users"] user_db = collection.find_one_and_update(query_str, newvalues) user = UserInDB(**user_db) return user
def search_items( q: str, skip: int = 0, limit: int = 100, current_user: UserInDB = Depends(get_current_active_user), ): """ Search items, use Bleve Query String syntax: http://blevesearch.com/docs/Query-String-Query/ For typeahead suffix with `*`. For example, a query with: `title:foo*` will match items containing `football`, `fool proof`, etc. """ bucket = get_default_bucket() if crud.user.is_superuser(current_user): docs = crud.item.search(bucket=bucket, query_string=q, skip=skip, limit=limit) else: docs = crud.item.search_with_owner( bucket=bucket, query_string=q, username=current_user.username, skip=skip, limit=limit, ) return docs
def test_update_item(): title = random_lower_string() description = random_lower_string() id = crud.utils.generate_new_id() item_in = ItemCreate(title=title, description=description) bucket = get_default_bucket() user = create_random_user() item = crud.item.upsert(bucket=bucket, id=id, doc_in=item_in, owner_username=user.username, persist_to=1) description2 = random_lower_string() item_update = ItemUpdate(description=description2) item2 = crud.item.update( bucket=bucket, id=id, doc_in=item_update, owner_username=item.owner_username, persist_to=1, ) assert item.id == item2.id assert item.title == item2.title assert item.description == description assert item2.description == description2 assert item.owner_username == item2.owner_username
def route_users_put( *, username, password=None, admin_channels=None, admin_roles=None, disabled=None, email=None, full_name=None, ): current_user = get_current_user() if not current_user: abort(400, "Could not authenticate user with provided token") elif not check_if_user_is_active(current_user): abort(400, "Inactive user") elif not check_if_user_is_superuser(current_user): abort(400, "The user doesn't have enough privileges") bucket = get_default_bucket() user = get_user(bucket, username) if not user: return abort(404, f"The user with this username does not exist in the system.") user_in = UserInUpdate( username=username, password=password, admin_channels=admin_channels, admin_roles=admin_roles, disabled=disabled, email=email, full_name=full_name, ) user = update_user(bucket, user_in) return user
def test_check_if_user_is_active(): email = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=email, email=email, password=password) bucket = get_default_bucket() user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) is_active = crud.user.is_active(user) assert is_active is True
def remove(*, id: str) -> User: user = get(id=id) db = get_default_bucket() collection = db["users"] res = collection.delete_one({"id": str(id)}) return user
def get_multi(*, skip: int = 0, limit: int = 100): db = get_default_bucket() collection = db["users"] users = [] for user_db in collection.find(): user = UserInDB(**user_db) users.append(user) return users
def test_authenticate_user(): email = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=email, email=email, password=password) bucket = get_default_bucket() user = upsert_user(bucket, user_in, persist_to=1) authenticated_user = authenticate_user(bucket, email, password) assert authenticated_user assert user.username == authenticated_user.username
def init(): try: # Check Couchbase is awake bucket = get_default_bucket() logger.info( f"Database bucket connection established with bucket object: {bucket}" ) except Exception as e: logger.error(e) raise e
def init_tests(): # Check Couchbase is awake from app.db.database import get_default_bucket # noqa bucket = get_default_bucket() logger.info( f"Database bucket connection established with bucket object: {bucket}") # Wait for API to be awake, run one simple tests to authenticate test_get_access_token()
def test_check_if_user_is_superuser_normal_user(): username = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=username, email=username, password=password) bucket = get_default_bucket() user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) is_superuser = crud.user.is_superuser(user) assert is_superuser is False
def read_users( skip: int = 0, limit: int = 100, current_user: UserInDB = Depends(get_current_active_superuser), ): """ Retrieve users. """ bucket = get_default_bucket() users = crud.user.get_multi(bucket, skip=skip, limit=limit) return users
def test_check_if_user_is_superuser(): email = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=email, email=email, password=password, admin_roles=[RoleEnum.superuser]) bucket = get_default_bucket() user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) is_superuser = crud.user.is_superuser(user) assert is_superuser is True
def test_create_user(): email = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=email, email=email, password=password) bucket = get_default_bucket() user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) assert hasattr(user, "username") assert user.username == email assert hasattr(user, "hashed_password") assert hasattr(user, "type") assert user.type == "userprofile"
def route_users_search_get(q, skip=0, limit=100): current_user = get_current_user() if not current_user: abort(400, "Could not authenticate user with provided token") elif not check_if_user_is_active(current_user): abort(400, "Inactive user") elif not check_if_user_is_superuser(current_user): abort(400, "The user doesn't have enough privileges") bucket = get_default_bucket() users = search_users(bucket=bucket, query_string=q, skip=skip, limit=limit) return users
def test_check_if_user_is_active_inactive(): email = random_lower_string() password = random_lower_string() user_in = UserInCreate(username=email, email=email, password=password, disabled=True) bucket = get_default_bucket() user = upsert_user(bucket, user_in, persist_to=1) is_active = check_if_user_is_active(user) assert is_active is False
def route_recover_password(name): bucket = get_default_bucket() user = get_user(bucket, name) if not user: return abort( 404, f"The user with this username does not exist in the system.") password_reset_token = generate_password_reset_token(name) send_reset_password_email(email_to=user.email, username=name, token=password_reset_token) return {"msg": "Password recovery email sent"}
def create(*, obj_in: UserCreate) -> User: passwordhash = get_password_hash(obj_in.password) user = UserInDB(**obj_in.dict(by_alias=True), hashed_password=passwordhash) doc_data = jsonable_encoder(user) db = get_default_bucket() collection = db["users"] res = collection.insert_one(doc_data) user_db = collection.find_one({"_id": ObjectId(res.inserted_id)}) user = UserInDB(**user_db) return user
def get(*, id: ObjectId): db = get_default_bucket() collection = db["users"] query_str = {"id": str(id)} user_db = collection.find_one(query_str) if not user_db: return None user = UserInDB(**user_db) return user
def route_users_post_open(*, username, password, email=None, full_name=None): if not config.USERS_OPEN_REGISTRATION: abort(403, "Open user resgistration is forbidden on this server") bucket = get_default_bucket() user = get_user(bucket, username) if user: return abort(400, f"The user with this username already exists in the system") user_in = UserInCreate( username=username, password=password, email=email, full_name=full_name ) user = upsert_user(bucket, user_in) return user
def get_current_user(token: str = Security(reusable_oauth2)): try: payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM]) token_data = TokenPayload(**payload) except PyJWTError: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials") bucket = get_default_bucket() user = crud.user.get(bucket, username=token_data.username) if not user: raise HTTPException(status_code=404, detail="User not found") return user
def get_by_email(*, email: str) -> Optional[User]: query_str = {"email": f"{email}"} db = get_default_bucket() collection = db["users"] user_db = collection.find_one(query_str) if not user_db: return None user = UserInDB(**user_db) return user