diff --git a/api/kiwi_vpn_api/routers/_common.py b/api/kiwi_vpn_api/routers/_common.py index 3edf086..f9424bc 100644 --- a/api/kiwi_vpn_api/routers/_common.py +++ b/api/kiwi_vpn_api/routers/_common.py @@ -65,7 +65,7 @@ async def get_current_user( # can't connect to an unconfigured database if current_config is None: - return None + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) username = await current_config.jwt.decode_token(token) user = User.from_db(db, username) @@ -73,31 +73,40 @@ async def get_current_user( return user -async def get_current_user_if_admin( +async def get_current_user_if_exists( current_config: Config | None = Depends(Config.load), current_user: User | None = Depends(get_current_user), ) -> User: """ - Get the currently logged-in user if it is an admin. + Get the currently logged-in user if it exists. """ - # fail if not installed - if current_config is None: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) - # fail if not requested by a user if current_user is None: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + return current_user + + +async def get_current_user_if_admin( + current_config: Config | None = Depends(Config.load), + current_user: User = Depends(get_current_user_if_exists), +) -> User: + """ + Get the currently logged-in user if it is an admin. + """ + # fail if not requested by an admin if not current_user.is_admin(): raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + return current_user + async def get_current_user_if_admin_or_self( user_name: str, current_config: Config | None = Depends(Config.load), - current_user: User | None = Depends(get_current_user), + current_user: User = Depends(get_current_user_if_exists), ) -> User: """ Get the currently logged-in user. @@ -106,14 +115,8 @@ async def get_current_user_if_admin_or_self( and b) if it is not an admin. """ - # fail if not installed - if current_config is None: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) - - # fail if not requested by a user - if current_user is None: - raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) - # fail if not requested by an admin or self if not (current_user.is_admin() or current_user.name == user_name): raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) + + return current_user