fix: Simplify query that validates new username already exists

Instead of fetching all users and checking if the new username is present
in the list, we can directly query the database for the username.
This commit is contained in:
Michael Manganiello
2024-10-14 01:08:33 -03:00
parent 2a24f5f128
commit eba2971ffb
3 changed files with 22 additions and 3 deletions

View File

@@ -131,6 +131,22 @@ def test_add_user_from_unauthorized_user(
assert response.status_code == expected_status_code
def test_add_user_with_existing_username(client, access_token, admin_user):
response = client.post(
"/api/users",
params={
"username": admin_user.username,
"password": "new_user_password",
"role": Role.VIEWER.value,
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == HTTPStatus.BAD_REQUEST
response = response.json()
assert response["detail"] == f"Username {admin_user.username} already exists"
def test_update_user(client, access_token, editor_user):
assert editor_user.role == Role.EDITOR

View File

@@ -47,7 +47,8 @@ def add_user(request: Request, username: str, password: str, role: str) -> UserS
detail="Forbidden",
)
if username in [user.username for user in db_user_handler.get_users()]:
existing_user = db_user_handler.get_user_by_username(username)
if existing_user:
msg = f"Username {username} already exists"
log.error(msg)
raise HTTPException(

View File

@@ -12,11 +12,13 @@ class DBUsersHandler(DBBaseHandler):
return session.merge(user)
@begin_session
def get_user_by_username(self, username: str, session: Session = None):
def get_user_by_username(
self, username: str, session: Session = None
) -> User | None:
return session.scalar(select(User).filter_by(username=username).limit(1))
@begin_session
def get_user(self, id: int, session: Session = None) -> User:
def get_user(self, id: int, session: Session = None) -> User | None:
return session.get(User, id)
@begin_session