From: Michael Tremer Date: Mon, 16 Jun 2025 17:20:22 +0000 (+0000) Subject: API: Add helper function to fetch the principal X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=5491c65826e945d4ca01bf6c0e056bb6f24eeb41;p=pbs.git API: Add helper function to fetch the principal Signed-off-by: Michael Tremer --- diff --git a/src/api/auth.py b/src/api/auth.py index d5420f08..db960a03 100644 --- a/src/api/auth.py +++ b/src/api/auth.py @@ -77,6 +77,26 @@ def create_token(subject, type, expires_after, **kwargs): return jwt.encode(payload, TOKEN_SECRET, algorithm=TOKEN_ALGO) +def get_principal(token): + """ + Returns the authenticated principal from the given token + """ + try: + payload = jwt.decode(token, TOKEN_SECRET, algorithms=[TOKEN_ALGO]) + + # Fail if we could not decode the token + except jwt.InvalidTokenError as e: + print(e) + raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token") + + # Extract the principal + principal = payload.get("sub") + if not principal: + raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token") + + # XXX Should this hit the database to check the principal exists? + + return principal @router.post("/user") async def auth_user(credentials: fastapi.security.OAuth2PasswordRequestForm = @@ -117,18 +137,8 @@ class RefreshRequest(pydantic.BaseModel): @router.post("/refresh") async def auth_refresh(data: RefreshRequest): - try: - payload = jwt.decode(data.refresh_token, TOKEN_SECRET, algorithms=[TOKEN_ALGO]) - - # Fail if we could not decode the token - except jwt.InvalidTokenError as e: - print(e) - raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token") - - # Extract the principal - principal = payload.get("sub") - if not principal: - raise fastapi.HTTPException(status_code=401, detail="Invalid refresh token") + # Fetch the principal from the given token + principal = get_principal(data.refresh_token) # XXX Check if the principal actually still exists