refactor get_user_by_name_if_editable
This commit is contained in:
parent
5990577699
commit
fdce81c5a3
2 changed files with 35 additions and 15 deletions
|
@ -203,6 +203,20 @@ class User(UserBase, table=True):
|
||||||
) for capability in capabilities
|
) for capability in capabilities
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def can_edit(
|
||||||
|
self,
|
||||||
|
user: User,
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
Check if this user can edit another user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return (
|
||||||
|
user.name == self.name
|
||||||
|
# admin can edit everything
|
||||||
|
or self.can(UserCapabilityType.admin)
|
||||||
|
)
|
||||||
|
|
||||||
def owns(
|
def owns(
|
||||||
self,
|
self,
|
||||||
device: Device,
|
device: Device,
|
||||||
|
|
|
@ -105,27 +105,33 @@ async def get_current_user_if_admin(
|
||||||
|
|
||||||
async def get_user_by_name(
|
async def get_user_by_name(
|
||||||
user_name: str,
|
user_name: str,
|
||||||
|
current_config: Config | None = Depends(Config.load),
|
||||||
|
) -> User | None:
|
||||||
|
"""
|
||||||
|
Get a user by name.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# can't connect to an unconfigured database
|
||||||
|
if current_config is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
return User.get(user_name)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_user_by_name_if_editable(
|
||||||
|
user: User | None = Depends(get_user_by_name),
|
||||||
current_user: User = Depends(get_current_user_if_exists),
|
current_user: User = Depends(get_current_user_if_exists),
|
||||||
) -> User:
|
) -> User:
|
||||||
"""
|
"""
|
||||||
Get a user by name.
|
Get a user by name if it can be edited by the current user.
|
||||||
|
|
||||||
Works if a) the currently logged-in user is an admin,
|
|
||||||
or b) if it is the requested user.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# check if current user is admin
|
# fail if user doesn't exist
|
||||||
if current_user.can(UserCapabilityType.admin):
|
if user is None:
|
||||||
# fail if requested user doesn't exist
|
|
||||||
if (user := User.get(user_name)) is None:
|
|
||||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
||||||
|
|
||||||
# check if current user is requested user
|
# fail if user isn't editable by the current user
|
||||||
elif current_user.name == user_name:
|
if not current_user.can_edit(user):
|
||||||
pass
|
|
||||||
|
|
||||||
# current user is neither admin nor the requested user
|
|
||||||
else:
|
|
||||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
||||||
|
|
||||||
return user
|
return user
|
||||||
|
|
Loading…
Reference in a new issue